PHP

Customize Model Attributes with Eloquent Accessors and Mutators

Learn to automatically transform attribute values when retrieving or setting them on your Laravel Eloquent models using accessors (getters) and mutators (setters) for cleaner data handling.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = ['first_name', 'last_name', 'email', 'title'];

    /**
     * Get the user's full name.
     */
    public function getFullNameAttribute(): string
    {
        return "{$this->first_name} {$this->last_name}";
    }

    /**
     * Set the user's title.
     */
    public function setTitleAttribute(string $value): void
    {
        $this->attributes['title'] = ucfirst($value);
    }

    /**
     * Get the email attribute in lowercase.
     */
    public function getEmailAttribute(string $value): string
    {
        return strtolower($value);
    }
}

// Usage example:
$user = new User();
$user->first_name = 'John';
$user->last_name = 'Doe';
$user->email = '[email protected]';
$user->title = 'manager';
$user->save();

echo $user->full_name; // Output: John Doe
echo $user->email;     // Output: [email protected]
echo $user->title;     // Output: Manager
How it works: Eloquent accessors and mutators provide a convenient way to transform model attributes when you retrieve or set them. An accessor (e.g., `getFullNameAttribute`) automatically formats an attribute's value when it's accessed (e.g., `$user->full_name`), even for attributes not directly stored in the database. A mutator (e.g., `setTitleAttribute`) automatically manipulates an attribute's value before it's saved to the database (e.g., ensuring a title is capitalized). This pattern helps maintain data consistency and separates presentation logic from your application logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs