PHP

Defining Accessors and Mutators in Laravel Eloquent

Customize how your Eloquent model attributes are retrieved and saved by defining accessors for formatting data on retrieval and mutators for transforming data before saving.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class User extends Model
{
    protected $fillable = ['first_name', 'last_name', 'email', 'password'];

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

    /**
     * Set the user's first name.
     * Mutator: automatically called when setting $user->first_name = 'value'
     *
     * @param  string  $value
     * @return void
     */
    public function setFirstNameAttribute(string $value): void
    {
        $this->attributes['first_name'] = Str::ucfirst($value);
    }

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

    // To make 'full_name' available in JSON serialization, add to $appends
    // protected $appends = ['full_name'];
}
How it works: This code demonstrates how to use accessors and mutators in Laravel Eloquent. An accessor (`get{Attribute}Attribute`) automatically transforms an attribute's value when it is retrieved from the model, like concatenating first and last names into a full name. A mutator (`set{Attribute}Attribute`) automatically transforms an attribute's value before it is saved to the database, useful for tasks like formatting names or hashing passwords.

Need help integrating this into your project?

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

Hire DigitalCodeLabs