PHP

Customizing Attributes with Eloquent Accessors and Mutators

Discover how to use Eloquent accessors to format model attributes on retrieval and mutators to transform attributes before saving them to the database.

<?php

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

class User extends Model
{
    // Accessor: Called when retrieving the 'full_name' attribute
    // Method name format: get{AttributeName}Attribute
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }

    // Mutator: Called when setting the 'password' attribute
    // Method name format: set{AttributeName}Attribute
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    // Example: Mutator to capitalize first name before saving
    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = ucwords($value);
    }

    // Example: Accessor to format creation timestamp
    public function getCreatedAtFormattedAttribute()
    {
        return $this->created_at->format('M d, Y H:i A');
    }
}

// Example Usage (e.g., in a controller or route)
$user = new App\Models\User();
$user->first_name = 'john';
$user->last_name = 'doe';
$user->email = '[email protected]';
$user->password = 'secret'; // Mutator will hash this
$user->save();

// Access the full name (accessor will concatenate)
echo $user->full_name; // Outputs: John Doe

// Access the formatted creation time
echo $user->created_at_formatted; // Outputs: e.g., Jan 01, 2023 10:30 AM
How it works: Accessors and mutators allow you to transform Eloquent model attributes when they are retrieved from or saved to the database. An accessor method (prefixed with `get` and suffixed with `Attribute`) automatically runs when you access an attribute, allowing you to format or combine data. A mutator method (prefixed with `set` and suffixed with `Attribute`) automatically runs when you set an attribute, enabling transformations like hashing passwords or capitalizing names before they are persisted. This provides a clean way to encapsulate attribute-level logic within your models.

Need help integrating this into your project?

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

Hire DigitalCodeLabs