Master Laravel Eloquent: Accessors, Mutators, and Attribute Casting Explained

Learn how Laravel Eloquent’s accessors and mutators let you automatically format attribute values, how to define custom getters and setters, configure date conversion with Carbon, customize date formats, and use the $casts property to transform JSON, arrays, booleans, and other data types.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Master Laravel Eloquent: Accessors, Mutators, and Attribute Casting Explained

Laravel Eloquent provides mechanisms—accessors, mutators, and attribute casting—to automatically transform model attributes when they are retrieved or saved.

Accessors & Mutators

Defining an accessor

To create a custom accessor, add a method named getFooAttribute to the model, where Foo is the camel‑cased attribute name. The method receives the raw value from the database and should return the transformed value.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user's first name with the first letter capitalized.
     */
    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }
}

Usage:

$user = App\User::find(1);
$firstName = $user->first_name; // Returns capitalized value

Accessors can also compute derived values:

public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

Defining a mutator

To modify a value before it is persisted, define a setFooAttribute method. The method receives the incoming value and should assign the transformed value to the model’s internal $attributes array.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Store the user's first name in lowercase.
     */
    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = strtolower($value);
    }
}

Example:

$user = App\User::find(1);
$user->first_name = 'Sally'; // Stored as 'sally'

Date conversion

Eloquent automatically casts created_at and updated_at to Carbon instances. The set of date attributes can be customized via the $dates property or disabled entirely.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $dates = ['created_at', 'updated_at', 'deleted_at'];
}

To change the storage format, set the $dateFormat property. For example, storing timestamps as UNIX seconds:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    protected $dateFormat = 'U';
}

Attribute type casting

The $casts array defines how attributes are converted when accessed or set. Supported cast types are:

integer

float

string

boolean

object

array

collection

date

datetime

timestamp

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

Now $user->is_admin will always be a boolean regardless of the integer stored in the database.

Array & JSON casting

When a column stores JSON or serialized text, casting it to array (or object) automatically deserializes the value into a PHP array. Assigning an array back will re‑serialize it to JSON.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $casts = [
        'options' => 'array',
    ];
}

Example usage:

$user = App\User::find(1);
$options = $user->options; // JSON decoded to array
$options['key'] = 'value';
$user->options = $options; // Array encoded to JSON on save
$user->save();
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPLaravelEloquentMutatorsAccessorsAttribute Casting
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.