Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bradycharron's avatar

Date casting in query

I have a scope that applies to one of my models. It accepts a Carbon date instance that I am using to filter the results of the query. It is filtering on a date column, and when I pass the raw Carbon instance in to the where clause, it does not format the date correctly. I am expecting the format to be 'Y-m-d' and it is using 'Y-m-d H:m:s'. I have tried to cast the date field with the $casts property on my model, but it does not seem to have am impact for the query. Do casts work for queries?

Example code:

public function scopeWithMinDate(
    \Illuminate\Database\Eloquent\Builder $query,
    \Carbon\Carbon $date,
    string $operator = '='
): \Illuminate\Database\Eloquent\Builder
{
    return $query->where('min_date', $operator, $date);
}
0 likes
2 replies
aurawindsurfing's avatar

Hi @bradycharron

In your model use:

protected $casts = [
        'min_date' => 'date',
    ];

instead of:

protected $casts = [
        'min_date' => 'datetime',
    ];
bradycharron's avatar
bradycharron
OP
Best Answer
Level 1

I had tried this without success. I did find that use whereDate for the query did the trick though.

1 like

Please or to participate in this conversation.