Laravel 5.0 - Eloquent Attribute Casting

(This is part of a series of posts on New Features in Laravel 5.0.)

  1. Laravel 5.0 - Form Requests
  2. Laravel 5.0 - ValidatesWhenResolved
  3. Laravel 5.0 - Directory structure and namespace
  4. Laravel 5.0 - Route Caching
  5. Laravel 5.0 - Cloud File Drivers
  6. Laravel 5.0 - Method Injection
  7. Laravel 5.0 - Route Annotations (removed)
  8. Laravel 5.0 - Event Annotations (removed)
  9. Laravel 5.0 - Middleware (Filter-style)
  10. Laravel 5.0 - Environment Detection & Environment Variables
  11. Laravel 5.0 - Event Scheduling
  12. Laravel 5.0 - Commands & Handlers
  13. Upgrading from Laravel 4 to Laravel 5
  14. Bringing Whoops Back to Laravel 5
  15. Laravel 5.0 - Events & Handlers
  16. Laravel 5.0 - Generating Missing Events
  17. Laravel 5.0 - Custom Error Pages
  18. Laravel 5.0 - Eloquent Attribute Casting

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 integer or boolean.

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.

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, real, 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.

string #

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 #

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 #

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.

Conclude #

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!


Comments? I'm @stauffermatt on Twitter


Tags: laravel 5 | laravel | eloquent

Matt Stauffer headshot

Hi, I'm Matt Stauffer.

I'm partner & technical director at Tighten Co.

You can find me on Twitter at @stauffermatt


Like what you're reading?

I wrote an entire 450+ page book for O'Reilly: Laravel: Up and Running.

You can order the eBook or print book today.