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.
Accessors and mutators in 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.
full_name attribute by joining first and last names.public function getFullNameAttribute() {
return $this->first_name . ' ' . $this->last_name;
}public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}created_at date when accessed.public function getCreatedAtAttribute($value) {
return date('d-m-Y', strtotime($value));
}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.
<?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'
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.
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.