Accessors are used to format the attributes when you retrieve them from database. Whereas, Mutators are used to format the attributes before saving them into the database.
Lets get started
*Creating Accessors *
Suppose that you have two column
first_name & last_name in users table
Now you want to get the user full_name
. Accessors create a "fake"
attribute on the object which you can access as if it were a database column. So if your person has first_name
and last_name
attributes, you could write User Model
:
`Syntax to create accessor –
To define an accessor, create a get{Attribute}Attribute method on your model where {Attribute} is the “studly” cased name of the column.`
Model User.php
protected function getFullNameAttribute()
{
return $this->fist_name . "" . $this->last_name;
}
and a Controller that looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class AccessorMutatorController extends Controller
{
//get accesor userFullName
public function getUser()
{
$users = User::get();
foreach($users as $user){
echo $user->full_name;
}
}
}
also a route
that looks like this:
Route::get('accessor',[AccessorMutatorController::class,'getUser']);
Creating Mutators
A mutator transforms an Eloquent attribute value when it is set. Mutators work when we save data inside database table.
Syntax to create mutators –
To define a mutator, define a set{Attribute}Attribute
method on your model where {Attribute} is the “studly” cased name of the column which we want to get altered when saved.
Model User.php
// when "name" will save, it will convert into lowercase
protected function setNameAttribute($value){
$this->attributes['name'] = strtolower($value);
}
and a Controller that looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class AccessorMutatorController extends Controller
{
//setUser with mutator
public function setUser()
{
$user = new User();
$user->name = "Alan Donald";
$user->fist_name = "Alan";
$user->last_name = "Donald";
$user->email = "jone@gmail.com";
$user->password = bcrypt("123456");
$user->save();
}
}
also a route
that looks like this:
Route::get('mutator',[AccessorMutatorController::class,'setUser']);
Check the result
The result should look something like this:
Hurray! We have successfully created and used accessors and mutators , use this on your future projects to improve the readability , stability and performance of your code!