1.

What are accessors and mutators?

Answer»

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.

Conclusion

LARAVEL is the most used PHP FRAMEWORK for web development. Laravel interviews CONSIST of questions about a deep UNDERSTANDING of PHP MVC architecture and app development BASICS like routes, controllers, views, and advanced topics such as Service Container, Dependency Injection, Accessors & Mutators, etc.



Discussion

No Comment Found