Laravel - Mutators / Casts - Attribute Casting

Attribute casting provides functionality similar to accessors and mutators without requiring you to define any additional methods on your model. Instead, your model's $casts property 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. The supported cast types are:

To demonstrate attribute casting, let's cast the is_admin attribute, which is stored in our database as an integer (0 or 1) to a boolean value:


After defining the cast, the is_admin attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:

    $user = App\Models\User::find(1);
    if ($user->is_admin) {

If you need to add a new, temporary cast at runtime, you may use the mergeCasts method. These cast definitions will be added to any of the casts already defined on the model:

        'is_admin' => 'integer',
        'options' => 'object',
Attributes that are null will not be cast. In addition, you should never define a cast (or an attribute) that has the same name as a relationship.