PHP

Create Custom Eloquent Accessors and Mutators

Transform model attributes on retrieval and before saving using Laravel Eloquent accessors and mutators, ideal for formatting, encryption, or computed properties.

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

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

class User extends Model
{
    use HasFactory;

    // Accessor: Combines first_name and last_name into a 'full_name' attribute
    public function getFullNameAttribute(): string
    {
        return "{$this->first_name} {$this->last_name}";
    }

    // Mutator: Hashes the password before saving to the database
    public function setPasswordAttribute(string $value):
    {
        $this->attributes['password'] = bcrypt($value);
    }
}

// Usage Example:
$user = User::find(1);

// Accessor usage
echo $user->full_name; // Outputs: John Doe

// Mutator usage
$user->password = 'new-secure-password'; // Automatically bcrypts the password
$user->save();
How it works: Accessors enable you to transform model attributes when they are retrieved (e.g., creating a `full_name` from `first_name` and `last_name`). Mutators allow you to modify an attribute's value before it is saved to the database (e.g., hashing a password). These features provide a clean and automatic way to handle data formatting, sanitization, or encryption 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