Attribute Casting in Laravel Eloquent Models

Attribute Casting in Laravel Eloquent Models

Spread the word! Share with your fellow developers.

Laravel Eloquent provides a convenient way to change the data type of attributes using attribute casting. 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 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 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. Please feel free to comment below your questions.

One comment on “Attribute Casting in Laravel Eloquent Models

Leave a Reply

Your email address will not be published. Required fields are marked *



This site uses Akismet to reduce spam. Learn how your comment data is processed.