26th Oct 17By John Doe

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.

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_login
  • 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 indonesian 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: