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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php namespace laranaija; use IlluminateDatabaseEloquentModel; class Car extends Model { /** * Get the car's name. * * @param string $value * @return string */ public function getNameAttribute($value) { return strtoupper($value); } } |
Now, if the name of the second record in cars table is ‘jaguar’, then calling the name attribute now would be:
1 2 3 4 5 |
$car = Car::find(2); $name = $car->name; // result would be JAGUAR, all in uppercase |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace laranaija; use IlluminateDatabaseEloquentModel; class Car extends Model { /** * Set the car's color. * * @param string $value * @return string */ public function setColorAttribute($value) { $mutant = '50 shades of ' . $value $this->attributes['color'] = $mutant; } } |
Now if we assign a value to the car’s color attribute like so:
1 2 3 |
$car = Car::find(2); $car->color = 'Grey'; |
..and assess the color of the car like so:
1 2 3 |
echo $car->color; // result would be 50 shades of grey |
The concept is that simple!
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.
- How to build your own Youtube – Part 10 - August 1, 2016
- How to build your own Youtube – Part 9 - July 25, 2016
- How to build your own Youtube – Part 8 - July 23, 2016
- How to build your own Youtube – Part 6 - July 6, 2016
- Introducing Laravel Password v1.0 - July 3, 2016
- How to build your own Youtube – Part 5 - June 28, 2016
- How to build your own Youtube – Part 4 - June 23, 2016
- How to build your own Youtube – Part 3 - June 15, 2016
- How to build your own Youtube – Part 2 - June 8, 2016
- How to build your own Youtube – Part 1 - June 1, 2016