Laravel Accessors and Mutators

Laravel accessors and mutators are custom, user defined methods that allow you to format Eloquent attributes. Accessors are used to format attributes when you retrieve them from the database, while mutators format the attributes before saving them to the database.

Defining an accessor

Syntax for defining an accessor is getFooAttribute() where Foo is capitalized attribute you want to access. If your attribute is first_name, and you want to be sure that first name will always be camel cased when you fetch it, you’ll need to define an accessor function as follows:

For sure, that’s one of the most commonly used examples when you read about accessors, but you can use it to format dates, prices etc.

Let’s say you have a Member model with following fields:

  • first_name
  • last_name
  • email
  • password
  • last_visit
  • settings
  • created_at
  • updated_at

We have few fields where we can take an advantage of using accessors. For example, users are often careless and you want to make sure that first name and last name are always capitalized.

To create a Member, you would probably use code similar to this (and yes, we’ll simulate user input here):

Even if I was lazy member and didn’t care to  properly capitalize my own name, you  would probably still want to display my name correctly. Right? Accessors do just that:

You can also use accessors to combine two real attributes to create just one. In this example, it’s easy to imagine what I’m referring to – full name. You can create accessor method like this:

Then you would use it as if it really exists in the database:

You can play it with the dates to. With accessors you can chose the how the dates should be displayed. In most european countries date format is different than in the US. With accessors you can show the date in the format that is familiar to your users. For example:

When you call last_login  attribure, you’ll have following output:

Defining an mutator

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 our first_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.

Json Encoding

If you look at our Member model once again, you’ll notice settings  attribute which is used to store users personal preferences and options you provide in your app. Of course, you would use an array to manage those options and one of the best options to store an array to the database is to encode it as an JSON string. Some of the databases have long history of JSON data types, such as PostgreSQL, first with json, and with latest relase we got new superfast jsonb datatype. As of MySQL 5.7.8, MySQL introduced json data type so (even) if you use MySQL you can still store JSON objects into it.

For the settings  attribute you should have both accessor to decode JSON string to an array and mutator to encode an array to JSON object:

Full example

At the end, here is a complete Member model I’ve used in this article:

and how to use it:


I really hope that I helped you understand what accessors and mutattors are, and if you don’t already use them I hope you now have an idea for what you can use them in your projects.

Follow me

Mirza Pasic

Full Stack Developer at OLX
Web Developer. Geek. Systematic. Dreamer
Follow me

Published by

Mirza Pasic

Web Developer. Geek. Systematic. Dreamer

  • tzs007

    Hi Mirza!

    I relatively new to Laravel, I’ve started to learn 4 months ago, but I have 15 years experience in web. I understood mutators and accessors in these days, but I did’nt find anything about mutate Model properties with multiple variables, like:

    public function setNetPriceAttribute($price, AppointmentRequest $request)
    $this->attributes[‘gross_price’] = $price * $request->tax; // tax came from my form via Request obj

    Can you help me, how can I get external properties, variables, whatever from inside the mutator or accessor?

    Thank you

    • Attila Fulop

      Your gross price is rather a calculated field, so I would rather store net_price and tax with the model, and calculate gross price on the fly, as described here and here

      If you stick to persisting the gross_price to the database, then you hook to the model’s saving event as described here