PHP

Transform Eloquent Attributes with Accessors and Mutators

Learn to automatically format Eloquent model attributes on retrieval (accessor) or modification (mutator) for cleaner data presentation and storage in Laravel.

// In your User model
class User extends Model
{
    /**
     * Get the user's full name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
            set: fn (string $value) => [
                'first_name' => explode(' ', $value)[0],
                'last_name' => explode(' ', $value)[1] ?? '',
            ],
        );
    }

    /**
     * Get the user's first name. (Old style accessor for comparison)
     *
     * @param  string  $value
     * @return string
     */
    // public function getFirstNameAttribute($value)
    // {
    //     return ucfirst($value);
    // }

    /**
     * Set the user's password. (Old style mutator for comparison)
     *
     * @param  string  $value
     * @return void
     */
    // public function setPasswordAttribute($value)
    // {
    //     $this->attributes['password'] = bcrypt($value);
    // }
}

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

$user->full_name = 'John Doe'; // Uses the fullName mutator
$user->save();
// $user->first_name is now 'John', $user->last_name is 'Doe'
How it works: Eloquent accessors and mutators allow you to transform model attributes when they are retrieved from or saved to the database. Accessors (using `get` in `Attribute::make` or `getAttribute` suffix) modify attribute values before they are returned to your application, while mutators (using `set` in `Attribute::make` or `setAttribute` suffix) modify values before they are stored. This helps maintain data consistency and presentation logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs