I had completely forgotten to finish my 5.0 blog posts, but I saw a great quick to at Laravel 5 Eloquent Attribute Casting is Awesome, so I figured I would add it to my feature list. Check out the official Eloquent docs here.

What is attribute casting?

Casting a value means it to (or ensuring it is already) a particular type. Some types you might be familiar with are integer or boolean.

Attribute casting is a feature of models that allows you to set your model to automatically cast a particular attribute on your Eloquent model to a certain type.

Note: You could do this in the past, but you would have to automatically define a mutator for each attribute; now you can do it automatically with a single configuration array.

That means if you store your in a particular format in the database, and you want it to return in a different format, you can now cast it to the new format.

But why?

The most common uses for this will be when you store numbers—they’re returned as strings by default, but Eloquent attribute casting allows you to cast them as integer, , float, or double—or booleans—you can convert 0 and 1 in your database to true and false.

But that’s not all.

How does it work?

You cast attributes in Eloquent by adding a protected $casts array to your model.

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

As you can see, each entry in the array has the property slug as the key, and the cast type as the value. This $casts array is telling Eloquent: “Every time I access a property on this model named is_admin, please return it cast to type boolean.

The cast types

integer (or int)

This casts your field to an integer using return (int) $value.

float (or real or double)

Real, Float, and Double are the same thing in PHP. PHP’s (double) and (real) type casting are just aliases to (float); and if you check out the source, Eloquent is literally running return (float) $value for all three of these keys.


This casts your field to a string using return (string) $value.

boolean (or bool)

This casts your field to a boolean using return (bool) $value, which means you’ll likely be storing your values as 0 and 1.


Object and Array are the most interesting option. Both convert (deserialize) JSON-serialized arrays into PHP. Object uses return json_decode($value), returning a stdClass object.


Array deserializes JSON-serialized arrays into PHP arrays, using return json_decode($value, true), returning an array.

You can view the actual code for these in the source.


As you can see, Eloquent attribute casting has a ton of potential to free us up from unnecessary repetitive logic, and also sneakily makes it a lot easier to store data in JSON in our database. Good Stuff!

Source link


Please enter your comment!
Please enter your name here