简体   繁体   中英

How to add days in querying date? laravel

How can we add days in the date that we're querying using laravel eloquent?

Something like this:

Post::where('created_at + 7 days', now()->toDateTimeString())
    ->where('created_at', '<', now()->toDateTimeString())
    ->get();

My logic is like this one

today >= created_at && today <= created_at + 4

Is there some correct syntax to achieve this one?

One of the ways to compare from date time is using the calculated Carbon like below:

Post::where('created_at', '>=', now()->addDays(4)->toDateTimeString()
    ->get();

It will display only posts which have created_at greater than 4 days from today.

For date range filter, you can use between scope like:

$startDate = now()->subDays(4)->toDateString();
$endDate = now()->toDateString();

$filteredPosts = Post::whereBetween('created_at', [$startDate, $endDate])->get();

For more information about filter, you could visit Laravel Query Builder

You can use whereDate method:

Post::whereDate('created_at', 'like', now()->subDays(4))->get();

or

Post::whereDate('created_at', '>=', now()->subDays(4))->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM