'Laravel 5.4: How do I get records from just this week?

To get all records of the current day, I did

$dt = Carbon::now();
$dataToday = Data::whereDay('created_at', $dt->day)->get();

To get records from this week, I tried the following but without success.

$dataThisWeek = Data::where('created_at', $dt->weekOfYear);
$dataThisWeek = Data::where('created_at', $dt->weekOfMonth);
$dataThisWeek = Data::whereWeek('created_at', $dt->week);

How do we approach this with Eloquent and Carbon (preferably) or a native MYSQL function?



Solution 1:[1]

Try this:

Data::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();

To set the week start/end:

Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);

Solution 2:[2]

You can also try

$dataThisWeek = Data::where(\DB::raw("WEEKOFYEAR(created_at)"), $dt->weekOfYear)->get();

Solution 3:[3]

For some reason using Laravel 7.4^ the accepted solution above is not working on my end. No data is shown, to fix it I added a format like this:


$now = Carbon::now();

Data::whereBetween("created_at", [
   $now->startOfWeek()->format('Y-m-d'), //This will return date in format like this: 2022-01-10
   $now->endOfWeek()->format('Y-m-d')
])->get();

Solution 4:[4]

To complete @user320487 answer:

To avoid conflict between different third-party libraries, static setters should not be used. Use $weekEndsAt optional parameter instead when using endOfWeek method.

Data::whereBetween('created_at', [Carbon::now()->startOfWeek(Carbon::SUNDAY), Carbon::now()->endOfWeek(Carbon::SATURDAY)])->get();

You can also use the 'first_day_of_week' locale setting to change the start of week according to current locale selected and implicitly the end of week.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ayip
Solution 3 Darwin Marcelo
Solution 4 Mohammed Bensouna