Javier Núñez Fernández Full Stack Web Engineer

Laravel Eloquent Accessors & Mutators: Why would I need them?

Laravel Eloquent Accessors & Mutators

I did not know nothing about Accessors and Mutators. I had heard about them sometimes but I never needed them. In the project I am currently working on I had some requirements for the backend that led me to find something to help me.

THE QUESTION

I had a MySQL field with JSON information in it. Everytime I get that field I had to convert with json_decode to a PHP array. So I wonder:

Is there something already on Laravel that let me change a field before getting it from database?

THE ANSWER IS: ACCESSORS

Yes, I found that accessors are there for that. What is an accessor? It is just a function that resides on your model and is executed after the standard model "get" function. So, it's like overriding the function that get that field from database. For example, in my case, I had this:

	
	/**
	 * Accessor to decode JSON before returning it
	 */
	public function getJsonContentAttribute($value) {
		return json_decode($value);
	}

*** Be careful, the name of the function must be with get first and then the model field name written in CamelCase. getFieldNameInCamelCase()

AND...WHAT ABOUT MUTATORS?

As you may have wonder is the other way around. With a mutator you can execute a function before a set (or save) function is executed.


	/**
	 * Set the user's first name.
	 *
	 * @param  string  $value
	 * @return string
	 */
	public function setFirstNameAttribute($value)
	{
	    $this->attributes['first_name'] = strtolower($value);
	}

EXAMPLES OF USE

  1. You want to store in DB a user name and surname always be stored in this format: john SMITH, you could use a mutator to modify the fields before save. It would be something like this:
  2. 
    public function setName($value) {
        $this->attributes['name'] = strtolower($value);
    }
    
    public function setSurname($value) {
        $this->attributes['surname'] = strtoupper($value);
    }
    
  3. In your DB you have a field (e.g. colours) stored by commas (e.g. "red,green,orange") that come from a form multiple select. Every time you get that field, you want to get the array of these values to be able to work with it. You could use an accessor to do it:
    
    public function getColours($value) {
       return explode(',', $value);
    }
    

REFERENCE