Understanding Mutators and Accessors in Laravel: Simplifying Data Manipulation

Aman jain
5 min readJul 4, 2023

In this article , We will understand about the mutator and accessor with an example.

Introduction

Accessors and Mutators are like handy tools in web development that help us write cleaner and more organized code while following the principle of “Don’t Repeat Yourself.”

What are Mutators ?

In Laravel’s Eloquent models, mutators also called setters ,allow programmers to change an attribute’s value before the database is populated with it. This is especially helpful if you need to alter the data or format it in accordance with particular business standards.

Implementation of Mutators:

Let’s take an example to explain this. Consider a User model with a “name” attribute. To capitalize the first letter of every word in the name before storing it, you can define a mutator method named setNameAttribute.

/**Set the "name" attribute and automatically capitalize it.
@param string $value
@return void
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = ucwords($value);
}
  • The naming standard for mutator methods is as follows: the method name begins with set is followed by the name of the attribute in CamelCase, and is concluded with Attribute.
  • The code snippet represents a mutator method called setNameAttribute within a class.
    The value to be entered for the name property is specified as a parameter called $value that the method takes.
  • The method uses the ucwords() function, a built-in PHP function, to capitalize the value provided.
  • The capitalized value is then assigned to the $this->attributes[‘name’] array, which represents the underlying attribute storage of the class.
  • By using this mutator, whenever the name attribute is set, it will automatically capitalize the value before storing it.
  • This can be useful in scenarios where consistent capitalization is desired for the name attribute, preventing the need to manually capitalize the value each time it is assigned.
  • By consolidating the logic into a single method, the mutator follows to the DRY (Don’t Repeat Yourself) concept, improving maintainability and minimizing duplication.
  • Other parts of the code can simply set the name attribute directly, and the mutator will handle the capitalization automatically.

What are Accessors ?

Accessors, also called getters, give developers the ability to retrieve and modify attribute values before showing them to users or using them further in the application. Accessors offer a great approach to package transformations and deliver data in a more palatable or appropriate format.

Implementation of Accessors:

Let’s say you want to capitalize the “title” consistently throughout your application and you have a “Post” model with a title attribute. You can define an accessor to take care of this for you rather than manually converting the title each time you fetch a post.

/**Get the value of the "title" attribute and 
return it with the first letter capitalized.
@param string $value
@return string
*/
public function getTitleAttribute($value)
{
return ucfirst($value);
}

Explanation of this example:-

  • The naming standard for accessors methods is as follows: the method name begins with get is followed by the name of the attribute in CamelCase, and is concluded with Attribute.
  • When you access the “title” attribute of a Post model instance, this method will be automatically called.
  • The title attribute’s initial value, which is kept in the variable $value, is passed to the method.
  • It uses the ucfirst() function to capitalize the first letter of the title.
    The modified title is then returned as the result of the accessor method.
  • So, whenever you access the “title” attribute, it will automatically retrieve the value with the first letter capitalized.

Using Mutators and Accessors Together.

Accessors and mutators can be used together in Laravel models to provide custom behavior for both reading and writing attribute values. Here’s an example that combines both accessors and mutators in a Laravel model:

   class MyModel extends Model
{
/**Accessors
* Get the title attribute and apply modifications before returning.
*
* @param string $value
* @return string
*/
public function getTitleAttribute($value)
{
return ucfirst($value);
// Capitalize the first letter of the title
}

/**Mutators
* Set the title attribute and apply modifications before storing.
*
* @param string $value
*/
public function setTitleAttribute($value)
{
$this->attributes['title'] = strtolower($value);
// Convert the title to lowercase
}
}

Now we see how we can access in a Controller.

use App\Models\MyModel;
class MyController extends Controller
{
public function show($id)
{
// Retrieve the model instance
$model = MyModel::find($id);

// Accessor method (getTitleAttribute) is automatically called
$title = $model->title;

// Mutator method (setTitleAttribute) is automatically called
$model->title = 'new title';


// Save the changes to the model
$model->save();

// Redirect or render the view with the updated data
return view('my-view', ['title' => $title]);
}
}

Explanation

  • Retrieve an instance of the MyModel model with the desired $id using the find method. This retrieves the model from the database based on the provided ID.
  • Access the title attribute just like any other attribute of the model. In this example, $model->title is used. This triggers the accessor method (getTitleAttribute), which automatically modifies the value of the attribute. The modified value is then stored in the $title variable.
  • As though it were a normal property, change the value of the title attribute.. Assign the desired value to $model->title.
  • This triggers the mutator method (setTitleAttribute), which automatically modifies the value before assigning it to the attribute.
  • In this example, the mutator converts the value to lowercase before assignment.
  • Save the changes to the model using the save method. This persists the updated data, including the modified “title” attribute, in the database.
  • Finally, redirect or render a view, passing the updated data to the view as needed. In this example, the view may receive the $title variable, which contains the modified value of the “title” attribute, and use it to display the updated data to the user.

🏃‍♂️💨 Hurree, we finally learned 🧪 mutator and accessor methods! 🎉📚.

Best Practices and Additional Features: To make the most out of Mutators and Accessors in Laravel, consider the following best practices:

  1. Consistent Naming: Follow Laravel’s naming conventions by prefixing mutators with set and accessors with get, followed by the camel-cased attribute name.
  2. Attribute Availability: Ensure that the attribute you wish to modify or access is present in the model’s $attributes array or is a database column.
  3. Attribute Casting: Laravel provides attribute casting functionality that allows you to define the expected data types for specific attributes. This simplifies data manipulation and automatically handles type conversion when setting or retrieving attributes.
  4. Virtual Attributes: Laravel enables the creation of virtual attributes that do not have corresponding columns in the database. You can define mutators and accessors for these virtual attributes just like any other attribute.

🆓📝 Feel free to subscribe for more engaging content! 👏💬 Share your thoughts in the comments and spread the article with anyone you enjoyed it with. As it always has been, I appreciate your support and thanks for reading! 🙏📚

If you want to learn about SOLID principles in Laravel, you can read this article: 📖😊

https://medium.com/@jaffery0314/laravel-route-mission-method-47662c328d8

“👩‍💻💪 Code with passion, shape the future. Embrace challenges, create wonders. Your dedication can change the world. ✨”

--

--