Attribute Casting in Laravel Eloquent Models

Attribute Casting in Laravel Eloquent Models

Laravel Eloquent provides a convenient way to change the data type of attributes using attribute casting. Let’s explore the Laravel Eloquent this feature.

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to.

Attribute casting means, changing the value of an attribute to a particular data type like boolean, integer, strings or array.

To cast an attribute value of a Laravel Eloquent model, all you have to do is add them to the $casts property of the model class with their desired type. Like below:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
    protected $casts = [
        'featured'  =>  'boolean',
        'qty'       =>  'integer'

Now, whenever we access the values of featured attribute, it will be converted to boolen and same for qty which will be converted to integer. Like below,

dd($product->featured); // true

The $casts property should be an array where the key is the name of the attribute and value is the type of attribute being cast. The supported cast types for Laravel Eloquent models are:

  • object
  • array
  • integer
  • real
  • float
  • double
  • string
  • boolean

Object and array, both convert JSON Serialized arrays into PHP. Object deserializes uses json_decode($value) returning a stdClass object while array deserializes uses json_decode($value, true) returning a PHP array.

That’s it for today about Laravel Eloquent. Please feel free to comment below your questions.

Your little help will keep this site alive and help us to produce quality content for you.