Laravel 10 Upgrade: Eloquent Deprecated $dates – Change to $casts – Zaigo Infotech Software Solutions

Let’s craft brilliance together!

Request a free consultation and get a no-obligation quote for your project within one working day.

Company-Logo

Error: Contact form not found.

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

Laravel

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:

 

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:

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:

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:

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:

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:

And now your date will be formatted as you specified:

This also works with the date cast:

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.

 

 

Can't find what you are looking for?

Post your query now, and we will get in touch with you soon!

    Want to start a project?

    Our team is ready to implement your ideas. Contact us now to discuss your roadmap!

    GET IN TOUCH

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    INDIA

    9thfloor, (9A & 9B) Sapna Trade Centre, 135,
    Old 109, Poonamallee High Rd, Egmore,
    Chennai, Tamil Nadu 600084

    +91 9884783216

    marketing@zaigoinfotech.com

    USA

    170 Post Rd #211, Fairfield,
    CT 06824,
    USA

    +1 904-672-8617

    sales@zaigoinfotech.com