LARAVEL

Accessors and Mutators in Laravel 5


Getters and Setters are common concepts in programming. Every language has a particular construct of making this possible. These concepts are also termed Accessors and Mutators.

Accessors and Mutators allow you to format attributes when retrieving them from a model or setting their value.

Laravel 5 makes good use of these beautiful concepts in Models.

There are situations where you’ll want to manipulate the data been returned by Models just before presenting it to the users. For instance, let’s say we have a Car Model with properties of name and color and we want to have the name in capital letters, it’s very simple to implement that using Accessors and Mutators in Laravel 5 like so:

Note: name and color attributes simply means they are column names in the cars table.

Accessors

Now, if the name of the second record in cars table is ‘jaguar’, then calling the name attribute now would be:

Mutators:

The syntax for setting a mutator is simply setColumnAttribute where Column refers to the column name you want alteration for its values.

Note: the Column should be Camel case. e.g if the column name is last_name, then the mutator function would be setLastNameAttribute

Now if we assign a value to the car’s color attribute like so:

..and assess the color of the car like so:

The concept is that simple! :smile:

Note: laranaija is my namespace, yours by default would be App unless you change it to a custom one.

Please, let me know if you have any questions in the comment section.

PROSPER OTEMUYIWA

About PROSPER OTEMUYIWA

Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.