Jens Segers on

Laravel 5 Eloquent attribute casting is awesome

Attribute casting is a new feature of Laravel's Eloquent model that was recently added without really getting much attention (yet). So what does it do, and how can you use it?

Casting is, implicitly or explicitly, changing the entity of one data type into another. A simple example is casting the string "100" to its integer representation:

$value = "100"; // $value is a string
$value = (int) "100"; // $value is an integer

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

public function getAgeAttribute($value)
    return (int) $value;

But not anymore! Laravel 5 recently added attribute casting which makes this process a bit easier. To cast specific attributes, add them to the $casts property of the model class with their desired type:

protected $casts = [
    'age' => 'integer'

Now, whenever you access the age attribute, it will be converted to an integer by Eloquent.

var_dump($user->age); // int(25)

For me personally, this will be especially useful when working with boolean values. Boolean values are usually stored as a TINYINT in the database, and when Eloquent fetches the model again, they are returned as a "1" or "0" string. "Luckily" for us, PHP does some type juggling and implicitly converts it to the correct boolean values. But shit will hit the fan if you pass the JSON version of your model to javascript.

user = {
    "id": "1",
    "username": "jens",
    "activated": "0"

user.activated ? "yes" : "no"; // will output "yes"

By adding the activated property to new $casts property, the value will be automatically converted to a boolean, and won't cause problems in javascript.

    "id": "1",
    "username": "jens",
    "activated": true


Tweet about this blog post and you will appear below!