26th Oct 17By John Doe

Laravel accessors and mutators are custom, user defined methods that allow you to format Eloquent attributes. Mutators format the attributes before saving them to the database.

Syntax for defining a mutator function is setFooAttribute()  where Foo is a camel cased column you want to access. So, once again, let’s use ourfirst_name  and last_name  columns, but this time we want to make change before saving it to the database:

You probably notice that here we don’t return anything. We directly access the attribute and set a new value. With this approach we can be sure that first and last name will always be capitalized.

More examples

I’ve shown you just a few very basic examples of accessor and mutator functions. But you can do a lot more and I’ll give you a few other situations where you can use them.

HASHING PASSWORDS

I’m sure you want to encrypt passwords when you save them into database, right? Mutators are really good way to ensure this:

This way you know that password attribute will be always hashed before it’s inserted into DB. Here I used Laravel’s Hash facade to create password hash, but you could also use bcrypt()  helper method.