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.
Comment And Like System Using Disqus
Generate Sitemap in PHP Laravel
Ensure text remains visible during Webfont load
Install Apache Web Server On Ubuntu 20.04 / Linux & Manage It
Create Custom 404 Page In Laravel
Laravel Clear Cache Of Route, View, Config Command
Create Gmail App Password For SMTP Mails
Factories To Speed Up Test-Driven Development In Laravel
Why You Should Run Cronjobs In Laravel?
Free SSL Certificate For CPanel
Test Your Local Developing Laravel Web Application From Phone Browser Without Any Software
Custom Validation Rules In PHP Laravel (Using Artisan Command)