Skip to content

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:

/**
 * The attributes that should be casted to native types.
 *
 * @var array
 */
protected $casts = [
    'is_active' => 'boolean',
];

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

dd($user->is_active); // true

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:

public function getIsActiveAttribute($value)
{
    return (int) $value;
}
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments