Search code examples
phplaraveleloquentphp-carbon

whereBetween in Laravel not working well with Carbon


I want to query the users who created at 2016-01-10. So code in Laravel 5.1 like this (the created_at is timestamp):

$day1 = new Carbon();
$day1->year = 2016;
$day1->month = 1;
$day1->day = 10;

$day2 = new Carbon();
$day2->year = 2016;
$day2->month = 1;
$day2->day = 11;

User::whereBetween('created_at', [$day1->startOfDay(), $day2->startOfDay()])->get();

The codes above works fine. But this normal way, does not:

User::whereBetween('created_at', [$day1->startOfDay(), $day1->endOfDay()])->get();

I don't think there is a difference.


Solution

  • You don't need a between for this:

    $myDate = new Carbon('2016-01-10');
    User::whereDate('created_at', '=', $myDate->format('Y-m-d'))->get();