PHP

Transform Model Attributes with Eloquent Mutators and Accessors

Learn how to use Eloquent accessors to format attribute values when retrieved and mutators to transform values before they are saved to the database.

// In app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // ...

    /**
     * Get the user's first name. (Accessor)
     *
     * @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. (Accessor only)
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function fullName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->first_name . ' ' . $this->last_name,
        );
    }
}

// In a controller or service
use App\Models\User;

$user = User::find(1);

// Accessor: 'first_name' will be capitalized
echo "First Name (Accessor): " . $user->first_name . "
";

// Accessor: 'full_name' is dynamically generated
echo "Full Name (Accessor): " . $user->full_name . "
";

// Mutator: 'first_name' will be lowercased before saving
$user->first_name = 'JOHN';
$user->save();
// In database, first_name would be 'john'
echo "Saved First Name (via Mutator): " . $user->first_name . "
"; // Still capitalized when accessed after save due to accessor
How it works: Accessors allow you to transform Eloquent attribute values when you retrieve them from a model instance. Mutators allow you to transform attribute values before they are saved to the database. Using `Illuminate\Database\Eloquent\Casts\Attribute` (Laravel 9+), you can define both `get` (accessor) and `set` (mutator) logic for a single attribute, or just `get` for computed properties, simplifying data presentation and ensuring consistent data storage.

Need help integrating this into your project?

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

Hire DigitalCodeLabs