Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 67 ยท Eloquent ORM

Accessors, Mutators and Casts

Transform Eloquent attributes on the way in and out: Attribute accessors and mutators, built-in, enum, JSON, encrypted and custom casts, plus appends and hidden.

The database stores strings, integers and text. Your application wants booleans, enums, arrays, money objects and nicely formatted names. Something has to translate between the two, and you do not want that translation scattered across controllers and views, where it will be done slightly differently every time.

Eloquent gives you two tools for it. Accessors and mutators are small functions that run when you read or write one attribute. Casts declare, once, that a column has a certain type, and Eloquent converts values in both directions automatically. This lesson covers both, plus the settings that control how a model is turned into an array or JSON for an API. You should already know basic models from Eloquent models and CRUD. The Laravel code is read-only, as Laravel cannot run on this site; the TryIt blocks are PHP stand-ins that reproduce how the mechanism works.

Accessors and mutators with Attribute

An accessor changes a value when you read it; a mutator changes it when you assign it. Since Laravel 9 you define both in one method that returns an Attribute object. The method name is the camelCase form of the snake_case column:

PHP
use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Model
{
    protected function firstName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower($value),
        );
    }

    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) =>
                $attributes['first_name'].' '.$attributes['last_name'],
        );
    }
}

$user->first_name = 'ADA';      // stored as "ada"
echo $user->first_name;         // "Ada"
echo $user->full_name;          // computed, there is no full_name column

The get function receives the raw column value, and as a second argument all raw attributes, which is how a virtual attribute like full_name can combine columns. The set function returns what to store. It can also return an array to set several columns at once, such as splitting an address object into address_line1 and address_line2.

Two practical notes. First, accessors run every time the attribute is read; if the work is expensive, add ->shouldCache() to the Attribute. Second, an accessor is for presentation or derived values. If it grows into business logic with queries inside it, move that into a normal method, because an innocent-looking $user->full_name should never hit the database.

Casts

Accessors work for one-off tweaks. When a column has a type, use a cast. In Laravel 13 you declare them in a casts() method on the model:

PHP
protected function casts(): array
{
    return [
        'is_admin'     => 'boolean',
        'options'      => 'array',
        'published_at' => 'datetime',
        'price'        => 'decimal:2',
        'status'       => PostStatus::class,
        'api_token'    => 'encrypted',
        'password'     => 'hashed',
    ];
}

From now on $user->is_admin is a real bool, $post->published_at is a Carbon date you can call ->diffForHumans() on, and assigning a PostStatus value stores its string. A few casts deserve a closer look:

  • array / json / collection: the column holds JSON text. Reading gives a PHP array (or collection); assigning an array stores JSON. Note that changing a nested value in place, $user->options['theme'] = 'dark', does not work on a plain array cast: read, change, then assign the whole array back. AsArrayObject and AsCollection allow in-place changes.
  • Enum casts: point a column at a backed enum class and you get enum cases in PHP and the backing values in the database. An invalid stored value throws a ValueError, which is useful: bad data is noticed early. See class constants and enums for enums themselves.
  • encrypted (also encrypted:array): values are encrypted with your APP_KEY before storage and decrypted on read. Remember that you cannot search or sort by an encrypted column, and that losing or rotating the key without a plan makes the data unreadable.
  • hashed: hashes a value on assignment, ideal for passwords. It cannot be reversed, so there is no read-back.
  • datetime and date: parse strings into Carbon objects and format them for the database. Prefer immutable_datetime if you want immutable dates.

null is never cast: a null column stays null, so write code that expects that.

Here is a stand-in for the mechanism. It stores raw strings the way a database would and converts them on the way in and out:

PHP A tiny cast system with an enum and a custom cast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The raw array is exactly what would sit in the table (1, JSON text, the enum's string, integer cents), while the model's public face hands out true, an array, an enum case and a Money object. A bad value in the database fails loudly the moment it is read.

Custom casts

When no built-in cast fits, write your own class that implements CastsAttributes (the interface the stand-in imitated). It has a get method that turns the database value into your object and a set method that turns it back:

PHP
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class AsMoney implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): Money
    {
        return new Money((int) $value, $attributes['currency']);
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): array
    {
        return ['price' => $value->cents, 'currency' => $value->currency];
    }
}

The real signatures receive the model, the key and all raw attributes, so one cast can read and write several columns (here, price and currency). If you only need to transform data on the way in, implement CastsInboundAttributes with just set. Value objects such as Money, Address or Coordinates are the best use of custom casts: your domain code receives a meaningful type rather than loose columns.

Controlling arrays and JSON

When a model is returned from a route or an API Resource (see API resources), Eloquent calls toArray(). Four properties shape the output:

PHP
class User extends Model
{
    protected $hidden = ['password', 'remember_token'];   // never exported
    protected $appends = ['full_name'];                    // accessors to add
}

$user->makeVisible('password');       // one-off override
$user->makeHidden(['email']);

$hidden keeps secrets out of JSON. $visible does the opposite, as an allow list. $appends adds accessor-based values that are not real columns, so full_name appears in the JSON. Always hide password hashes and tokens, and prefer explicit API Resources for public APIs, so that a new column does not leak by accident.

PHP already has a built-in class named Attribute (for attributes like #[Override]), so the stand-in below calls its version Attr.

PHP Accessors, mutators, hidden and appends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The mutator lowercases the value on the way in, the accessor capitalizes it on the way out, the address mutator fans one string out into two columns, password is missing from the output and full_name appears even though no such column exists.

flowchart LR
    A["$model->price = new Money(1999)"] -->|"cast set()"| B["Database<br/>price = 1999"]
    B -->|"cast get()"| C["$model->price<br/>(Money object)"]
    C -->|"toArray(): hidden, appends"| D["JSON for the API"]

Casts convert values in both directions; toArray decides what leaves the model.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about the Attribute class is correct?

    The accessor (get) runs on read and the mutator (set) on assignment. get can also compute virtual attributes from other columns.
  2. 2. You store a settings array in a JSON column with the 'array' cast. How do you change one nested value?

    Indirect modification of a plain array cast does not persist. You assign the complete array back, or use AsArrayObject or AsCollection.
  3. 3. Why is an enum cast helpful when the database contains an unexpected value?

    Backed enums reject values that are not one of their cases, so corrupted or outdated data is noticed instead of passing through.
  4. 4. What is the effect of putting 'password' in a model's $hidden property?

    $hidden only affects serialization. The attribute remains readable and writable in code.
  5. 5. Which is a good reason to avoid encrypted casts on a column?

    The database sees only ciphertext, so where clauses and ordering on the real value cannot work.

Summary

  • Accessors and mutators are defined with Attribute::make(get:, set:) in a camelCase method and run on attribute reads and writes; virtual attributes can combine columns.
  • The casts() method declares column types: boolean, array/json, datetime, decimal, enum classes, encrypted and hashed.
  • A null value is never cast, and an in-place change to a plain array cast does not persist.
  • Custom casts implement CastsAttributes and are ideal for value objects such as money or addresses.
  • $hidden, $visible and $appends control what toArray() and JSON output contain; hide secrets and prefer API Resources for public data.

Next: Model Events, Observers and Soft Deletes