What is Eloquent model casting in laravel

Models are returned in the JSON format as they are represented in the database. Often, model attributes, which are Boolean in nature, are represented by 0 and 1 for true and false, respectively. It may be, in this case, more convenient to return a real true and false to the RESTful call’s return object.

In Laravel 4, this was done using accessors. If the value was $status, the method would be defined as follows:

public function getStatusAttribute($value){
    //do conversion;
}

In Laravel 5, this process is much easier, thanks to a new feature called model casting. To apply this technique, simply add a protected key and a value array called $casts to the model as follows:

class Room extends Model
{
    protected $casts = ['room_number'=>'integer','status'=>'boolean'];
    public function accommodation(){
        return $this->belongsTo('\MyCompany\Accommodation');
    }
}

In this example, room_number is a string, but we want to return an integer. Status is a tiny integer, but we want to return a Boolean value. Casting these two values in the model will modify the resultant JSON in the following manner:

{"id":1,
"room_number": "101",
"status": 1,
"created_at":"2015-03-14 09:25:59",
"updated_at":"2015-03-14 19:03:03",
"deleted_at":null,
"accommodation_id":2}

The preceding code will now change as follows:

{"id":1,
"room_number": 101,
"status": true,
"created_at":"2015-03-14 09:25:59",
"updated_at":"2015-03-14 19:03:03",
"deleted_at":null,
"accommodation_id":2}

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares