PHP

Transform Model Data with Laravel Eloquent Accessors and Mutators

Learn to automatically format or modify attribute values when retrieving (accessor) or saving (mutator) data with Laravel Eloquent. Enhance data presentation and integrity.

// In your App\Models\User model:
namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute; // For Laravel 9+
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class User extends Model
{
    // Laravel 9+ way (recommended)
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value), // Accessor: capitalize name on retrieve
            set: fn (string $value) => strtolower($value), // Mutator: store name as lowercase
        );
    }

    // Example of a virtual attribute (not backed by a database column)
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn () => "{$this->first_name} {$this->last_name}",
        );
    }

    // Older Laravel versions (pre-9) using separate methods
    // public function getNameAttribute(string $value): string
    // {
    //     return ucfirst($value);
    // }

    // public function setNameAttribute(string $value): void
    // {
    //     $this->attributes['name'] = strtolower($value);
    // }
}

// Usage example:
use App\Models\User;

$user = User::create([
    'first_name' => 'John',
    'last_name' => 'Doe',
    'name' => 'alice smith', // Will be stored as 'alice smith' (lowercase by mutator)
    'email' => '[email protected]',
    'password' => bcrypt('password')
]);

// Accessing the 'name' attribute triggers the accessor
echo "User Name: " . $user->name . "
"; // Output: Alice smith (capitalized)

// Accessing the 'fullName' virtual attribute
echo "Full Name: " . $user->fullName . "
"; // Output: John Doe

$user->name = 'BOB JOHNSON'; // Triggers the mutator
$user->save();
echo "Updated User Name: " . $user->name . "
"; // Output: Bob johnson
How it works: Accessors and mutators (now unified as model attributes in Laravel 9+) allow you to transform Eloquent attribute values when they are retrieved from or saved to the database. Accessors (via the `get` method) let you format or modify values for presentation (e.g., capitalizing a name), while mutators (via the `set` method) enable modification before saving (e.g., ensuring an attribute is always lowercase). They can also create virtual attributes that don't exist in the database, like `fullName`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs