Search code examples
phplaravelphp-carbon

How to get results of the weekend laravel


I’m trying to get results of the weekend in laravel. I would like to show all the events of the weekend during all the week. So I would like to show all results from monday to sunday, but just weekend events. I have:

$friday = Carbon::parse('this friday')->toDateTimeString();
$sunday = Carbon::parse('this sunday')->toDateTimeString();
if (Carbon::now()->gt(Carbon::parse('this friday'))) {
        $friday = Carbon::parse('last friday')->toDateTimeString();
}
$events = Event::where([
        ['date', '>=', $friday],
        ['date', '<=', $sunday]
    ])
        ->orderBy('date', 'asc')
        ->get();

But when it’s satuday this doesn’t work. I don’t know how to do it. Any idea? Thanks!


Solution

  • Firstly, you can use code:$dt = Carbon::now(); $dt->isWeekend(); to check is weekend or not, then calculate the $friday date and $sunday date.