Laravel 10 Upgrade: Eloquent Deprecated $dates - Change to $casts

With the release of Laravel 10, you might have noticed that the $dates property on your Model stopped working properly. It has been deprecated in favor of $casts, let me show you what to do.

Here's an example:

class Expense extends Model
{
protected $fillable = [
'name',
'amount',
'expense_date',
];
 
protected $dates = [
'expense_date'
];
 
// ...
}

Now, if you want to show $expense->expense_date, the problem is that it no longer returns a Carbon object. It results in the following being returned:


Moving Away From $dates to $casts

Keeping the $dates property doesn't break your code, but it also doesn't transform your date attributes into Carbon instances anymore:

{{-- ... --}}
<td>{{ $expense->expense_date->format('d/m/Y') }}</td>
{{-- ... --}}

This results in the following:

This is because the $dates property has been deprecated in favor of the $casts property. The $casts property is more flexible and allows you to cast your attributes to different types, not just dates.

To adapt to the new change, just add your date attributes to the $casts property:

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

And that's it! Now if you dump the same date as before - you will see that it's now a Carbon instance:

But what if you want to cast your date with time? For that, you can use the datetime cast:

// ...
protected $casts = [
'expense_time' => 'datetime',
];
// ...

And now you will see that your date is a Carbon instance with time:

This means that you can now format it as you wish:

{{-- ... --}}
<td>{{ $expense->expense_date->format('d/m/Y') }}</td>
{{-- ... --}}

And it will work as expected:


Casting is More Flexible

With this change, you can expect even more flexibility. Remember earlier in Eloquent, you had to set formats in a $dateFormat property? Well, now you can do it directly in the $casts property:

// ...
protected $casts = [
'date' => 'datetime:Y-m-d H:i A',
];
// ...

And now your date will be formatted as you specified:

This also works with the date cast:

// ...
protected $casts = [
'date' => 'date:Y-m',
];
// ...


This deprecation change has been mentioned in the Laravel 10 Upgrade Guide. You can also read more about the $casts property in the official documentation

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 79 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials