PHP

Define Custom Accessors and Mutators in Eloquent

Enhance Eloquent models by defining custom accessors to format attributes on retrieval and mutators to transform attributes before saving to the database.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash; // For password hashing

class User extends Model
{
    use HasFactory;

    protected $fillable = ['first_name', 'last_name', 'email', 'password'];

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

    /**
     * Set the user's password (Mutator).
     *
     * @param  string  $value
     * @return void
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = Hash::make($value);
    }

    // Example usage:
    // $user = new User();
    // $user->first_name = 'John';
    // $user->last_name = 'Doe';
    // $user->email = '[email protected]';
    // $user->password = 'secret'; // Mutator will hash this
    // $user->save();
    //
    // echo $user->full_name; // Accessor will return 'John Doe'
}
How it works: Accessors and mutators allow you to transform Eloquent model attributes when you retrieve or set them. An accessor (e.g., `getFullNameAttribute`) automatically runs when an attribute is accessed, letting you format or combine values on the fly. A mutator (e.g., `setPasswordAttribute`) automatically runs when an attribute is set, enabling you to modify the value before it's saved to the database (e.g., hashing passwords). These methods improve data integrity and presentation without modifying raw database values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs