Skip to main content

Define accessors and mutators.

Published 2 min readMarkdown
Part of seriesLaravel
Define accessors and mutators.

Accessors allow you to transform the value of an Eloquent attribute when it is accessed. You can define an accessor by creating a protected method on the model to represent the accessible attribute. This method name should correspond to the "camel case" representation of the true underlying model attribute / database column

<?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.
     */
    protected function firstName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
        );
    }
}

You can access the value of the accessor by simply accessing the first_name attribute on a model instance:

use App\Models\User;

$user = User::find(1);

$firstName = $user->first_name;

Mutators allow you to transform an Eloquent attribute value when it is set. You can create a mutator by providing the set argument when defining your attribute.

<?php

namespace App\Models;

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

class User extends Model
{
    /**
     * Interact with the user's first name.
     */
    protected function firstName(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower($value),
        );
    }
}

Allows you to manipulate the value and return the manipulated value.

use App\Models\User;

$user = User::find(1);

$user->first_name = 'Sally';

The mutator will apply the strtolower function to the first_name and set its resulting value in the model's internal $attributes array.

About the author

  • Full Stack Developer with a passion for building web applications. PHP, Node.js, Laravel, MySQL, MongoDB. Love collaborating & making a difference

No comments yet. Be the first to comment.

More from this blog