← Back to all snippets
PHP

Transform Model Attributes with Accessors and Mutators

Customize how Eloquent model attributes are retrieved and saved to the database using accessors for formatting and mutators for processing data.

<?php

namespace App\Models;

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

class User extends Model
{
    protected $fillable = ['first_name', 'last_name', 'email', 'password'];

    // Accessor: Automatically formats the full name when accessed.
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
        );
    }

    // Mutator: Automatically capitalizes first name before saving.
    protected function firstName(): Attribute
    {
        return Attribute::make(
            set: fn (string $value) => ucfirst($value),
        );
    }

    // Mutator: Automatically hashes password before saving.
    protected function password(): Attribute
    {
        return Attribute::make(
            set: fn (string $value) => bcrypt($value),
        );
    }

    // Example usage:
    // $user = User::find(1);
    // echo $user->full_name; // Accesses the 'fullName' accessor

    // $user->first_name = 'john'; // Uses the 'firstName' mutator
    // $user->password = 'secret'; // Uses the 'password' mutator
    // $user->save();
}
How it works: Accessors and Mutators allow you to transform Eloquent model attributes when they are retrieved from or saved to the database. Accessors (e.g., `fullName()`) modify attribute values before they are returned to your application, perfect for formatting or combining fields. Mutators (e.g., `firstName()`, `password()`) modify attribute values before they are saved to the database, ideal for sanitization, encryption, or formatting input. The snippet uses Laravel 9+ `Attribute::make()` syntax for defining these.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs