Mutators and Accessors in Eloquent: A Practical Guide

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

In the world of Laravel’s Eloquent, an ORM for database manipulation, mutators and accessors are powerful features that allow developers to format attributes when you retrieve or set them on model instances. This practical guide will cover what mutators and accessors are, how to use them, and provide code examples to better understand their usage.

Getting Started

Let’s start by defining the terms:

  • Accessors in Eloquent are methods that allow you to manipulate attribute values after you obtain them from the database.
  • Mutators are methods that allow you to alter attribute values before you save them to the database.

An accessor method must be named with the prefix get, followed by the StudlyCase attribute name that you wish to access, followed by the suffix Attribute. Here’s a simple example:

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

With an accessor in place, you can now retrieve the full_name attribute from a user model instance as if it were a regular property:

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

Mutators are similarly named but use the prefix set. The following is an example that hashes a user’s password before saving it:

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

Now when you set the password attribute, the storage-ready hash is what’s saved:

$user = new User;
$user->password = 'plain-text-pass';
$user->save();

After understanding the basics, you might wonder how you can use mutators and accessors effectively. To demonstrate, let’s walk through several practical scenarios that you might encounter in real-world applications.

Formatting Dates

Accessors can be particularly useful for date formatting. For example, imagine you need to display the user’s created_at timestamp in a more readable format:

public function getCreatedAtAttribute($date) {
    return Carbon::parse($date)->format('m/d/Y');
}

Now, if you access the created_at attribute, Eloquent runs it through your accessor:

echo $user->created_at;  // Outputs '03/15/2023'

Adjusting Case

Suppose you want the user’s name to be automatically capitalized when setting it. A mutator can handle this easily:

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

Now, regardless of how the first name is entered:

$user->first_name = 'john';

It’s stored with an initial capital letter:

echo $user->first_name;  // Outputs 'John'

Encapsulating Business Logic

Mutators and accessors allow you to encapsulate business logic related to attribute formatting within your model. For example, if displaying a user’s full name involves a specific format, an accessor can take care of it:

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

Thus, you maintain the formatting logic in a single place rather than scattering it throughout your application:

echo $user->full_name;  // Outputs 'John DOE'

Working with Json Columns

Eloquent makes working with JSON columns in databases like MySQL or Postgres very sleek. You can use accessors and mutators to manipulate JSON data:

public function getOptionsAttribute($value) {
    return json_decode($value, true);
}

public function setOptionsAttribute($value) {
    $this->attributes['options'] = json_encode($value);
}

Then, when you interact with the options attribute, it feels like working with a regular array:

$user->options = ['newsletter' => true];
$user->save();

print_r($user->options);

Final Words

In this guide, we’ve covered what mutators and accessors are in Eloquent and how they can be used to ensure your data is formatted correctly both when retrieving and setting on your model instances. Implementing mutators and accessors following the guidelines and conventions provided by Eloquent will help you build robust MVC applications that handle data efficiently and elegantly.

Having many more facets and nuances, mutators and accessors are fundamental concepts in Laravel’s Eloquent ORM that shield the application logic from unnecessary clutter. By mastering their usage, you can enforce data integrity and create a more pleasant and predictable development experience. This tutorial was just the tip of the iceberg; as you grow more comfortable with these features, you’ll find them indispensable tools in your Laravel toolkit.