Search code examples
laraveldatephp-carbon

Laravel 5.4: select the records that's within 2 days only


I am need to pull all the records that's within 2 days only for example today is 24/7 so I need all the records in 23/7 and 22/7

I try this

->whereRaw('DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 2 DAY)')

but not working it gets the records from two days ago also try this

->whereDate( 'created_at', '>', Carbon::now()->subDays( 2 ) )

but it includes the records from today also which I don't want.

How should I do this using carbon or DATE


Solution

  • You should do:

    ->whereDate('created_at', '>', Carbon::today()->subDays( 2 ))
    ->whereDate('created_at', '!=', Carbon::today());
    

    This will exclude today.

    If you prefer a bit more raw queries then you can do:

    ->whereBetween(\DB::raw("DATE(`created_at`)"), [ Carbon::today()->subDays(2), Carbon::today()->subDays(1) ]);
    

    Note: Using today because it makes the code look more expressive but now would also work.