Laravel

What are accessors and mutators in laravel?

Kartic2 min read

Accessors are a way to retrieve data from eloquent after doing some operation on the retrieved fields from the database. For example, if we need to combine the first and last names of users but we have two fields in the database, but we want whenever we fetch data from eloquent queries these names need to be combined.

We can do that by creating an accessor like below:

public function getFullNameAttribute()	 	 
{	 	 
    return $this->first_name . " " . $this->last_name;	 	 
}

What the above code will do is it will give another attribute(full_name) in the collection of the model, so if we need the combined name we can call it like this: `$user->full_name`. Mutators are a way to do some operations on a particular field before saving it to the database.

For example, if we wanted the first name to be capitalized before saving it to the database, we can create something like the below:

public function setFirstNameAttribute($value)
{
    $this->attributes[‘first_name’] = strtoupper($value);
}

So, whenever we are setting this field to be anything:

$user->first_name = Input::get('first_name');
$user->save();

It will change the first_name to be capitalized and it will save to the database.

Share this articleLinkedIn X

Discussion (0)

Sign in to join the discussion.

Delete this comment?

This will also remove its replies.

Keep exploring

Laravel1 min read

What is Eloquent in Laravel?

Eloquent is the ORM used to interact with the database using Model classes. It gives handy methods on class objects to make a query on the database. It can directly be used to ret...

Kartic · Dec 22, 2022
Laravel1 min read

Explain Closures in laravel?

In Laravel, a closure is an anonymous function that often used as callback methods. Developers can also use it as a parameter in a function. Example: In Laravel, a closure is an an...

Kartic · Oct 24, 2019
Laravel1 min read

Session and Cookies in laravel

Session1. Retrieving Data from sessionsession()->get('key');2. Retrieving All session datasession()->all();3. Remove data from sessionsession()->forget('key'); or session()->flush(...

Kartic · Oct 24, 2019

Follow the engineering notes.

Subscribe for technical articles from iTechOrbit.