← Back to all snippets
PHP

Implementing Accessors and Mutators in Laravel Eloquent

Learn to use Eloquent accessors to format data when retrieved and mutators to transform data before it's saved to the database.

// app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function firstName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower($value),
        );
    }

    /**
     * Get the user's full name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->first_name . ' ' . $this->last_name,
        );
    }
}

// Example Usage
$user = App\Models\User::find(1);
$user->first_name = 'JOHN'; // Will be stored as 'john'
$user->save();

echo $user->first_name; // Will output 'John'
echo $user->full_name;  // Will output 'John Doe' (assuming last_name is 'Doe')
How it works: Accessors and Mutators allow you to transform Eloquent attribute values when they are retrieved from or set on a model instance. An accessor (`get`) will modify the attribute's value just before it's returned to your application, while a mutator (`set`) will modify it before it's saved to the database. As of Laravel 9+, the `Attribute::make` syntax provides a convenient way to define both getter and setter logic within a single method, offering a cleaner approach compared to older versions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs