DEV Community

Cover image for Attribute Casting with Laravel
Rafael França
Rafael França

Posted on • Originally published at Medium

Attribute Casting with Laravel

When was developing an application that use the MVC pattern, we need define our model, that is the layer that communicate our application with the database.

But sometimes, we need to casting values that received from model. Let me show an example:

You’re creating a model to represent Products, and need of: name, value, state (if it’s available or not) and when will it be available.

Every time that you need create, show or edit a product, need to casting the values. Our idea with this article is it makes your job easier, therefore, what about if we pass this responsibility to our model, so that it makes this automatically?

For this, Laravel has the $casts property. Let’s see how works:

Using this property, the attributes are casted automatically, and you not will need make this manually. Let’s see a practical example.

You’re create a method to add some days of delay in the availability of a product, for this, hasn’t used a date, only the quantities of days that want to delay.

Without use the $casts, you make something like this:

Note that we used the Carbon package to make a parse of the date and after add the quantities of days that want to be delayed.

And, if we use $casts, how would it be? Let’s see:

More simple and cleaner, sure?

You can think: “OK, I make this but, what I win, beyond save letters that will be typed?”.

The response to this question is: maintainability. That is, if in the future, you want to know the date and time that a product will be available, only need change your model, changing your $casts from date to datetime. It’s simple

What do you think about this tip?

Soon I back with more! :)

PS: Originally posted on my account on Medium.

Cover photo by Fotis Fotopoulos on Unsplash.

Top comments (0)