Mutators and Accessors in Laravel

laravel Jun 3, 2023

In the realm of object-oriented programming, encapsulation is a core concept that entails the bundling of data with methods that operate on that data. Laravel, being an eloquent representative of modern web frameworks, employs this concept via features known as accessors and mutators. This article delves into the specifics of mutators and accessors in Laravel and provides illustrative examples for better understanding.


What are Mutators?

Mutators in Laravel allow you to alter attribute values before saving them to the database. Essentially, when you're about to save a model, a mutator can be used to modify the data in some way.
Defining a Mutator
To define a mutator, you'll typically use the set{ColumnName}Attribute naming convention:

public function setColumnNameAtrribute($value)
{
  $this->attributes['column_name'] = strtolower($value)
}

Example:
Suppose you have a user's model and you want to ensure that the user's password is always hashed before it is saved.You can use a mutator:

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

Now whenever you set a password:

$user = new user();
$user->password = 'myPlainPassword';

it will automatically be hashed due to the mutator.

What are Accessors?

Accessors let you format attributes when you access them on a model. For instance, you can modify how a value is presented without altering the actual data stored in your database.
Defining an Accessor
To define an accessor you'll follow the get{ColumnName}Attribute convention:

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

Example:
If you want to always capitalize the first letter of a user's first name when accessing it, you could define an accessor like:

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

For a user instance with the first name 'john', accessing $user->firstName would yield John due to the accessor.
In Conclusion
Accessors and mutators in Laravel offer an elegant way to encapsulate and control the behavior of your model's data, ensuring that it adheres to certain criteria or is presented in a specific manner.

Tags