Table of Contents

Laravel Mutators

Mutators

A zombie developer does not sanitize data when sending or receiving it from their database, whereas a Laravel developer uses mutators to manipulate data before and after getting data from the database.

Mutators are our friends, and they will help us defeat the zombie developer apocalypse by helping us sanitize or manipulate data in our Models.


Mutators

Mutators allow us to change data before sending it to or retrieving it from the database. When we manipulate data before it gets entered into the database, it is referred to as a Mutator, when we manipulate data after we retrieve it from the database it is referred to as an Accessor.

We are going to use a pretty simple example to show you the basics of using mutators.

We will use our zombies table as an example from the previous sections. Let's say that anytime we get a zombie name from the database we want to make sure the name is capitalized. We could easily do this using an Accessor.

In our Zombie Model class from our past examples we would want to add the following method:

public function getNameAttribute($value){
    return ucwords($value);
}

And now any time we get a zombie name from the database it will be capitalized. You will want to make the name of the function correspond to the name of the database row you want to change. Since our database row was name our function name is getNameAttribute.

This can be done just as easy using Mutators, except we will modify the data before it gets put into the database. To add this mutator we would add the following method to our Zombie model:

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

The name would also be capitalized before we saved the data to the database. Our full Zombie Model with our Accessor and Mutator methods would look like the following:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Zombie extends Model {

    protected $table = 'zombies';

    public function getNameAttribute($value){
        return ucfirst($value);
    }

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

Most likely you wouldn't need the Accessor and Mutator to do the same thing, it would be a preference as to which one you wanted to use.

From the examples above, if anyone were to enter a zombie name into our database it would be capitalized. Hopefully, you can see the advantage of using mutators; it makes it easy to send and retrieve manipulated or formatted data from your database. Just another awesome functionality to help make our lives as developers easier.

Next up we are going to learn about views. Views are the files that typically contain the HTML & CSS. In the previous examples we have just been outputting our data from our routes\web.php file, but when we want to output data to the screen we will typically use our views. Let's move on to the next section to learn more.