I had completely forgotten to finish my Laravel 5.0 blog posts, but I saw a great quick introduction to attribute casting 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 changing it to (or ensuring it is already) a particular type. Some types you might be familiar with are
Attribute casting is a feature of Eloquent 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 data 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.
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
double—or booleans—you can convert
1 in your database to
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
The cast types
This casts your field to an integer using
return (int) $value.
Real, Float, and Double are the same thing in PHP. PHP’s
(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.
This casts your field to a boolean using
return (bool) $value, which means you’ll likely be storing your values as
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!