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 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 Chauhan
(Co-Founder)We Are Also Recommending You :
- [issue] Possible All Way To Change Asset Path And Add Public To Asset Path In Laravel
- Laravel 10 PDF Export Example With DomPDF
- Laravel One to One Eloquent Relationship Tutorial
- Error : Trying To Get Property Of ID Non-Object All Possible Solution Guideline In Laravel - PHP
- Cashfree Payment Gateway Integration In Laravel
- HTTP Client Guzzle Package With Basic Usage In Laravel
- How To Get Last Record From The Laravel Collection Using last() Collection Method Possible all Example
- How To Add Google reCAPTCHA v3 In HTML Form Based PHP/Laravel Website
- Laravel 9 Seeder and How to Seeding
- Laravel Routing Multiple Method Use In Single Route