Jens Segers on Jan 03 2015

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


terrasoff 9 months ago

... awesome until you gonna make your own casting type

Cortex Code 1 year ago

Thanks, this saved me a lot of time. :-)

Paulo Coghi 1 year ago

Sorry for the (semi)off-topic comment, but do you plan to create a "laravel-cassandra" project, following the same brilliant approach of laravel-mongodb?

asdasd 1 year ago


lloople 2 years ago

It's awesome, but I'm having trouble to save the data back to database. I cast a json string like 'object' and works pretty well, bu I tried to add new properties to that object $item->object_field->testing = true and then $item->save(); but the json string is not modified in the database. Any idea?

farzam 2 years ago

awesome post tnx for share with us

faruh 2 years ago

Very useful

mmachnicki 2 years ago

good to know, tnx ;)

dhrubojyoti das 2 years ago

Simple yet very very useful I just love Laravel

morrelinko 2 years ago

Nice Info

Miguel 2 years ago

Well written! :)

demo 2 years ago