Accessors and Mutators In Laravel

Laravel’s Accessors and Mutators are custom user defined methods that allows format eloquent attributes. Accessors allows to format attributes when data retrieved from database and Mutators format the attributes before saving them to database.

Accessor:

Syntax for defying an accessor is

1

getBarAttribute()

Where Bar is the capitalized attribute that you want to access. If your attribute is first_name and you want to be sure that first name always be in camel cased when you fetch it from database, you need to define accessor function like this:

1

2

3

4

publicfunctiongetFirstNameAttribute($value){

returnucfirst($value);

}

Honestly, this is the most common example for accessor when you search for an example accessor in Laravel. But you can use accessors for anything, like format date, prices like currency symbol or anything. Let’s day you have an employee model with the following attributes:

first_name

last_name

email

password

last_login

joining_date

created_at

updated_at

There are few fields where we can take advantage of the accessors. For example, employees can be careless enough and you want the first_name and last_name should always be capitalized. Now to create an employee, we can code something similar to the following simulating user input:

1

2

3

4

5

6

7

8

9

10

$user=App\Employee::create([

'first_name'=>'Jamir',

'last_name'=>'Hossain',

'email'=>'quantiklab@gmail.com',

'password'=>'blowmywhistle',

'last_login'=>Carbon\Carbon::now(),

'joining_date'=>Carbon\Carbon::now(),

'created_at'=>Carbon\Carbon::now(),

'updated_at'=>Carbon\Carbon::now()

]);

If the employee is lazy enough to care about capitalize first_name and last_name, you would still want to show them properly. Accessors can save your day.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

useIlluminate\Database\Eloquent\Model;

classEmployeeextendsModel

{

publicfunctiongetFirstNameAttribute($value)

{

returnucfirst($value);

}

publicfunctiongetLastNameAttribute($value)

{

returnucfirst($value);

}

}

Accessors can also be used to combine two real attributes and make one ! Like this:

1

2

3

4

publicfunctiongetFullNameAttribute()

{

returnucfirst($this->first_name).' '.ucfirst($this-&gt;last_name);

}

Now you can use it as it really exists in the database.

1

2

$employee=App\Employee::find(1);

echo$employee->full_name;

You can play this with date too. Using accessors, you can define how dates should be displayed. Date format is different in most European countries than USA. Using Accessors, you can easily format your date according to your need.

1

2

3

4

publicfunctiongetLastLoginAttribute($value)

{

return\Carbon\Carbon::parse($value)-&gt;format('d.m.Y.');

}

Now when you trigger last login attribute from Employee object you will find the following output:

1

2

3

4

$employee=App\employee::find(1);

echo$employee->last_login;

// 17.05.2016

Pretty fantastic. So you can present your data in any form using accessors in Laravel.

Mutators:

Syntax for defining a mutator method is

1

setBarAttribute()

What Bar is a camel cased column that you want to access. So once more let’s use our first_name and last_name column but this time will make changes before saving them to database.

1

2

3

4

5

6

7

8

9

publicfunctionsetFirstNameAttribute($value)

{

$this->attributes['first_name']=ucfirst($value);

}

publicfunctionsetLastNameAttribute($value)

{

$this->attributes['last_name']=ucfirst($value);

}

Notice any difference ? We did not “return” here anything as we directly access the attribute values and set new values to them. So with this approach we can be sure that whatever an employee types, first_name and last_name will always be capitalized.

Let’s go with another example. You always need to encrypt your password before save it to database. Mutators are really good in doing that.

1

2

3

publicfunctionsetPasswordAttribute($value){

$this->attributes['password']=Hash::make($value);

}

So it’s ensured that password will always be hashed before saving it to database. You can learn more about Laravel Hash facade in this link . However you can feel free to use

1

bcrypt

for password hashing.

I hope that this article will help you understand what accessors and mutators are, and if you don’t already familiar to them I think you now have an idea for what you can use them in your next projects.

Shibly is a *nix fan, open source enthusiast and passionate software engineer. He Loves music, hacking and playing PC video games. Currently he holds a 980ti SLI rig ! He also likes to play with anything cool. He is also a partner & technical director at QuantikLab

GET A WEB DEVELOPMENT QUOTE

Do you have a question about web design and development? We are prepare to answer all of your questions. We always assist our clients to run business smoothly in a complete technology agnostic way. We are devoted to provide the best in class services by maintaining the timeline. We guarantee perfection. Send us your requirements, we'll extract it, do necessary RnD and will provide you something that will definitely amaze you.

WHAT OUR CLIENT THINKS

QuantikLab is absolutely the best, their vary reliable and always on time.

William alkins

We have worked with many different offshore web development companies in the past. But would just like to say that the people at QuantikLab are the best! Extremely professional yet very personable! Very clean and scalable work and always right on time! Since we started working with them, never had to use another development company for any of our web design needs.

Jeff Anderson

Follow Us

LinkedIn

Skype

GitHub

About Company

QuantikLab Is an Outsourcing Web Design Company and We provide the BEST possible web business solution to our client that current technology allows within their budget. Repeating business and long lasting relationship is very important to us and we strive to maintain that.