Laravel 5 Eloquent – Attribute casting

One of the Laravel 5 awesome feature is Attribute casting. Casting attribute means changing the attribute values to a particular type. for example Boolean, integer, strings.

Eloquent models allows you to change datatype of the Attribute values automatically with Attribute casting feature.To cast a attribute of the model ,all you have to do is just add them to the $casts property of the model class with their desired type:

Now, whenever you access the is_active attribute, it will be converted to boolean by Eloquent.

The $casts property should be an array where the key is the name of the attribute being cast, while the value is the type you wish to cast to the column to. The supported cast types are: integer, real, float, double, string, boolean, object and array.

Object and Array Both convert JSON-serialized arrays into PHP. Array deserializes JSON-serialized arrays into PHP arrays, using return json_decode($value, true) and object uses return json_decode($value), returning a stdClass object.

In Laravel 4, you can add attribute casting by adding accessors/mutators to manipulate the attribute value:

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets. Protection Status