Query Records Created Between Two Dates in Laravel
Leonel Elimpe
by Leonel Elimpe
~1 min read

I have been trying to query records created between the start of the current month and the current date and time. If the current time is 2021-06-10 16:11:04, the query should return records created between 2021-05-01 and this time.

Initial attempts using whereDate() all gave inaccurate results.

<?php

ModelName::query()
    ->whereDate(
        'created_at',
        '>=',
        (new Carbon('first day of last month'))->toDateString()
    )
    ->whereDate(
        'created_at',
        '<=',
        now()->subMonthNoOverflow()
    )
    ->get();

I later found out whereDate() converts the date to the format 'Y-m-d' so the time is not considered (see below).

<?php

public function whereDate($column, $operator, $value = null, $boolean = 'and')
{
    // ...
    if ($value instanceof DateTimeInterface) {
        $value = $value->format('Y-m-d');
    }
    // ...
}

Using whereBetween() did the trick though! It worked exactly as wanted it to.

<?php

ModelName::query()
    ->whereBetween(
        'created_at',
        [
            (new Carbon('first day of last month'))->toDateString(),
            now()->subMonthNoOverflow()
        ]
    )
    ->get();


Further reading