PHP

Format Model Attributes with Eloquent Accessors & Mutators

Learn to transform Eloquent model attributes on retrieval (accessor) or before saving (mutator) for cleaner data handling, presentation, and data integrity.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
    ];

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

    /**
     * Set the user's first name, ensuring it's capitalized.
     *
     * @param string $value
     * @return void
     */
    public function setFirstNameAttribute($value)
    {
        $this->attributes['first_name'] = ucfirst($value);
    }

    /**
     * Set the user's email, ensuring it's lowercased.
     *
     * @param string $value
     * @return void
     */
    public function setEmailAttribute($value)
    {
        $this->attributes['email'] = strtolower($value);
    }

    // Example usage in a controller or elsewhere:
    // $user = User::find(1);
    // echo $user->full_name; // Accessor

    // $user->first_name = 'john'; // Mutator
    // $user->email = '[email protected]'; // Mutator
    // $user->save();
}
How it works: Eloquent accessors allow you to transform a model attribute when it is retrieved from the database. For example, `getFullNameAttribute` concatenates first and last names. Mutators allow you to transform a model attribute before it is saved to the database. `setFirstNameAttribute` automatically capitalizes the first name, and `setEmailAttribute` lowercases the email, ensuring consistent data storage. Both enhance data presentation and integrity without altering raw database values directly.

Need help integrating this into your project?

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

Hire DigitalCodeLabs