Attributes Casting, Accessors and Mutators in Laravel

Attributes Casting, Accessors and Mutators in Laravel

In this article, we are going to look into three of the Laravel Eloquent features attributes casting, accessors and mutators.

Attribute Casting

The easier way to transform your model attributes while accessing them is the attributes casting. In a few words, it lets you define what attribute you want to cast and what is going to be the destination type.

Suppose that you have another integer field in your product table: `is_available`. If the product is available, this will be equal to 1, 0 otherwise. However, when you work with it, the best thing would logically be as follows:

if($product->is_available)
  {
    // allow user to buy the product...
  }
  else
  {
    // show a message of availability with similar products...
  }

It will not be something like this:

if($product->is_available === 1)
  {
    // ...
  }

Right?

So, all you have to do to fix this problem is to specify, in your model, the casts array.

// app/Product.php
namespace App;

class Product extends Model {

protected $casts = [

    'is_available' => 'boolean',

];
}

From this moment, every time you call the is_available attribute, it will be automatically converted to the Boolean corresponding value and returned.

The supported types for casting are an integer, real, float, double, string, Boolean, object, and array.

Note

As also the documentation suggests, the array casting type is useful when you have a JSON array stored in a specific table column and you want to work with it quickly.

Accessors and Mutators

Attributes casting is very useful but has some limitations. Sometimes, starting from a simple value stored in the database, you need to do more complex work on it. Accessors and mutators are here to help.

To be more specific, an accessor is a method that is executed when the user reads a specific attribute. The accessor works on the attribute stored in the database and returns it. A mutator works in the opposite way: when you store a value, the mutator works does its job and then saves it in the table. Let’s say they are sorts of getters and setters.

Defining an accessor (or a mutator) is not so difficult: all you have to do is to follow a naming convention. Let’s start with something simple. Imagine that every time that you access the price of your product, you want to put the dollar symbol £ at the beginning of the string.

// app/Product.php
namespace App;

class Product extends Model {

  public function getPriceAttribute()
    {
        return '£ ' . $value;
    }

}

The naming convention for an accessor is simple as shown:

  1. The method name starts with get
  2. The middle part of the name is the attribute name, which is camel cased
  3. The method name ends with Attribute

Now, have a look at this:

$product = Product::find(1);

  echo $product->price;
  // output: £ 10.99

Every time you have the preceding code, the mutator is very similar. This time, we want to store a lowercase version of the product name.

namespace App;

class Product extends Model {

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

}

The convention isn’t changed so much: the only difference is that the method name now starts with set and not get.

Another real common use of mutators is when the application stores the user’s password. A mutator can be used to hash the chosen password and the result is then stored.

namespace App;

class User extends Model {

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

}

I hope you will find this helpful.

One comment on “Attributes Casting, Accessors and Mutators in Laravel

Leave a Reply

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

*

When sharing a code snippet please wrap you code with pre tag and add a class code-block to it like below.
<pre class="code-block">you code here</pre>

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.