0
0
Laravelframework~5 mins

Accessors and mutators in Laravel

Choose your learning style9 modes available
Introduction

Accessors and mutators let you change how data is read from or saved to your database in Laravel models. They help keep your code clean and consistent.

You want to format a date before showing it to users.
You need to automatically encrypt a password before saving it.
You want to change how a name is stored or displayed, like always capitalizing it.
You want to add a prefix or suffix to a value when reading it.
You want to convert stored data into a different type when accessing it.
Syntax
Laravel
class User extends Model {
    // Accessor
    public function getAttributeNameAttribute($value) {
        return ucfirst($value);
    }

    // Mutator
    public function setAttributeNameAttribute($value) {
        $this->attributes['attribute_name'] = strtolower($value);
    }
}

Accessor methods start with get, end with Attribute, and receive the original value.

Mutator methods start with set, end with Attribute, and receive the new value to store.

Examples
This accessor creates a new full_name attribute by joining first and last names.
Laravel
public function getFullNameAttribute() {
    return $this->first_name . ' ' . $this->last_name;
}
This mutator automatically encrypts the password before saving it.
Laravel
public function setPasswordAttribute($value) {
    $this->attributes['password'] = bcrypt($value);
}
This accessor formats the created_at date when accessed.
Laravel
public function getCreatedAtAttribute($value) {
    return date('d-m-Y', strtotime($value));
}
Sample Program

This example shows a User model with an accessor and mutator for the name attribute. When setting the name, it saves in lowercase. When getting the name, it returns with the first letter capitalized.

Laravel
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // Accessor to capitalize the name when accessed
    public function getNameAttribute($value)
    {
        return ucfirst($value);
    }

    // Mutator to store the name in lowercase
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = strtolower($value);
    }
}

// Usage example
$user = new User();
$user->name = 'ALICE'; // Mutator converts to 'alice'
echo $user->name; // Accessor converts to 'Alice'
OutputSuccess
Important Notes

Accessors and mutators only work on model attributes, not on regular methods.

Make sure method names exactly follow the getXAttribute and setXAttribute pattern, where X is the attribute name in StudlyCase.

Use accessors to format or modify data when reading, and mutators to change data before saving.

Summary

Accessors change how you get data from a model attribute.

Mutators change how you set data on a model attribute.

They help keep your data consistent and your code clean.