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…

--

--

Aman jain

I’m a developer who shares advanced Laravel and Node.js insights on Medium.