
Good content takes time and effort to come up with.
Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.
Accessors and mutators allow you to modify Eloquent attribute values when you fetch or set them on model instances.
For Eg: If you would like to transform or manipulate data before storing or while fetching from the database tables than you can you Mutators and Accessors respectively.
NOTE: Accessors & Mutators only works on eloquent models.
get
)The accessor will be called automatically by Eloquent when attempting to retrieve the value of the attribute.
To define an accessor, create a getFooAttribute
method on your model where Foo is the "studly" cased (meaning every word first letter will be capital, Eg: first_name of table column will become FirstName) name of the column you wish to access.
Eg: I want to add accessor to capitalize the first_name column of my table while fetching from the table then we need to create getFirstNameAttribute()
method in our model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getFirstNameAttribute($firstName)
{
return ucfirst($firstName);
}
}
Example
/** Here in table my name was saved like channaveer */
$user = User::find(1);
/** By using model first_name Laravel will automatically use accessor and manipulate the data before presenting you */
$user->first_name; /** Now the first_name will be Channaveer */
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $last_name;
}
set
)The Mutators will be called automatically by Eloquent when you want to store any value of the attribute in the database table.
To define a mutator, define a setFooAttribute
method on your model where Foo is the "studly" (meaning every word first letter will be capital, Eg: first_name of table column will become FirstName) cased name of the column you wish to write.
Eg: I want to add a mutator to lowercase the first_name column of my table while storing to table then we need to create setFirstNameAttribute()
method in our model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function setFirstNameAttribute($firstName)
{
$this->attributes['first_name'] = strtolower($firstName);
}
}
Hopefully, you will start implementing in your project and take advantage of it.
Facebook Login With PHP Laravel Socialite
Setup MAMP Virtual Hosts For Local PHP Development
Manipulate HTML Using DOMDocument In PHP
Factories To Speed Up Test-Driven Development In Laravel
Free SSL Certificate In cPanel With ZeroSSL & Certbot
Google reCAPTCHA Integration In PHP Laravel Forms
Laravel Clear Cache Of Route, View, Config Command
Laravel Last Executed Query In Plain SQL Statement For Debugging
Push Files To CPanel / Remote Server using FTP Software FileZilla
Debugging Laravel Queue Email Issues