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.
Why namespace And use Keywords Used In PHP
Accessors And Mutators In PHP Laravel
Resolve 404 Not Found In NGINX
Why You Should Run Cronjobs In Laravel?
Free SSL Certificate In cPanel With ZeroSSL & Certbot
PHP extension ext-intl * is missing
Generate Fake Data In PHP With Faker
Create A Composer Package? Test It Locally And Add To Packagist Repository
Testing Laravel Emails With MailHog
Website Speed and Performance Optimizations
Firebase Cloud Messaging (FCM) Browser Web Push Notifications Using Javascript And PHP
Simple Way To Create Resourceful API Controller In Laravel
Install Letsencrypt SSL Certificate for RabbitMQ Server and RabbitMQ Management Tool