What are accessors and mutators In Laravel

  • 31-01-2023
  • 379
  • Laravel 9
  • Haresh Chauhan

Using accessors we can run some operations with the data before inserting or fetching from the database in laravel eloquent query, you can do some operations with the specific column. for example, if you wish to collect data from the database with the user name and that user name should be "UPPERCASE" but the collection in the database is lowercase, so in this case using accessors we can transform the collected data into the "UPPERCASE".

For doing accessors in the laravel, use the below example. we can create an accessor like below example given.

Example 1

public function getFullNameAttribute()
{	 	 
    return strtoupper($this->first_name);	 	 
}

Now all collected data from the eloquent execute the query will return all the user fullname in the uppercase.

Example 2

Mutators are the use of doing some operation with the data before saving it in the database. For example, if you wish to insert the full name with the prefix like "MR.", let's play the below example in your application, this Mutators will insert the user's full name with the "MR." prefix before the name.

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

So, whenever we insert the full name in the database, it will insert with the prefix "MR." when you get the database from the database you will receive in the UPPERCASE string the full user name.

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

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :