A Guide to Understanding Accessors and Mutators in Laravel

A Guide to Understanding Accessors and Mutators in Laravel

Accessors and mutators are methods in Laravel's Eloquent ORM that allow you to manipulate the values of model attributes. Laravel Accessors and Mutators are simply user defined methods. Accessors are used to format the attributes when you retrieve them from database. On the other hand, Mutators are used to format the attributes before saving them into the database.

lets take a look at some samples:

 

Accessors

Accessors are used to modify the value of an attribute when it is retrieved from the database. For example, if you have an attribute called full_name that comprises of the first_name and last_name attributes, you can define an accessor to concatenate these two attributes:

public function getFullNameAttribute()
{
    return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}

Then, when you access the full_name attribute, Laravel will automatically call this accessor method to retrieve its value:

$user = User::find(1);
echo $user->full_name; // Maye Jacob

Example 2

if you have an "age" attribute on your User model, you could define an accessor like this:

public function getAgeAttribute($value)
{
    return $value * 2;
}

This would double the value of the "age" attribute whenever it is retrieved from the database.

 

Mutators

Mutators, on the other hand, are used to modify the value of an attribute before it is saved to the database. For example, if you want to store the password attribute in a hashed format, you can define a mutator like this:

public function setPasswordAttribute($value)
{
    $this->attributes['password'] = bcrypt($value);
}

Now, whenever you set the password attribute, Laravel will automatically call this mutator method to modify its value:

$user = new User;
$user->name = 'Maye Jacob';
$user->password = 'my-secret-password';
$user->save();
//or 
User::create([
	'name' => 'Maye Jacob',
	'password' => 'my-secret-password',
});

In this case, the setPasswordAttribute mutator will automatically hash the password value using Laravel's bcrypt function before storing it in the database.

To use an accessor or mutator, you simply need to name the method using the "camelCase" convention and prefix it with either "get" or "set", followed by the attribute name with the first letter capitalized.

For example, if you have a "first_name" attribute on your User model, you could define both an accessor and mutator like this:

public function getFirstNameAttribute($value)
{
    return ucfirst($value);
}

public function setFirstNameAttribute($value)
{
    $this->attributes['first_name'] = strtolower($value);
}

This would capitalize the first letter of the "first_name" attribute whenever it is retrieved from the database, and convert it to lowercase before it is saved to the database.

There is no limit to what you can do with accessors and mutators in laravel, it helps to make your code clean and easy to read and. 

in conclusion, accessors and mutators in Laravel are useful for manipulating model attributes in a consistent and flexible way, without having to modify the underlying data directly.

Attribute Casting

Attribute casting is a feature in Laravel's Eloquent ORM that allows you to define how your model's attributes should be stored and retrieved from the database. With attribute casting, you can specify that certain attributes should be cast to specific data types, such as booleans, integers, dates, and even custom classes.

To define attribute casting, you can use the $casts property in your model. This property is an array that maps attribute names to their respective data types. For example, if you have an is_admin attribute that should be treated as a boolean, you can define it like this:

protected $casts = [
    'is_admin' => 'boolean',
];

Now, whenever you retrieve a model that has the is_admin attribute, Laravel will automatically cast it to a boolean value, based on its original value in the database:

$user = User::find(1);
$is_admin = $user->is_admin; // true or false, depending on the value in the database

Similarly, you can cast attributes to other data types, such as integers, dates, and custom classes. For example, if you have a created_at attribute that should be treated as a Carbon instance, you can define it like this:

use Carbon\Carbon;

protected $casts = [
    'created_at' => 'datetime:Y-m-d H:i:s',
];

Now, whenever you retrieve a model that has the created_at attribute, Laravel will automatically cast it to a Carbon instance with the specified format:

$user = User::find(1);
$created_at = $user->created_at; // Carbon instance with the Y-m-d H:i:s format

You can even define your own custom attribute casts by creating a new class that implements the Illuminate\Contracts\Database\Eloquent\CastsAttributes interface, and registering it in your model's $casts property.

The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are:

  • array
  • AsStringable::class
  • boolean
  • collection
  • date
  • datetime
  • immutable_date
  • immutable_datetime
  • decimal:<precision>
  • double
  • encrypted
  • encrypted:array
  • encrypted:collection
  • encrypted:object
  • float
  • integer
  • object
  • real
  • string
  • timestamp

finally, attribute casting in Laravel provides a convenient way to work with your model's attributes in a more flexible and intuitive way, by defining how they should be stored and retrieved from the database.

 

 

Enjoy this article ? drop a comment below and add your own contribution.

Maye Jacob

Jacob Olorunmaye

Verified Expert
Passionate Backend Developer | Expert in PHP, Laravel, JavaScript, and Golang 🚀 | Crafting seamless, scalable solutions for the digital era

Leave a Reply

Your email address will not be published. Required fields are marked *