In this source book, we will learn what is Laravel Mutators, how to use Laravel Mutators with an example. Let’s explore the Laravel Mutators without wasting a second.
Table of Contents |
1. What Are Mutators In Laravel |
2. How To Define Mutators |
3. Example Of Mutators In Laravel |
01 What Are Laravel Mutators
The Mutators are used to format the attribute values while saving the data into the database. For example, you may want to save the Ecrypted
data into the database while saving records or creating records. Check the below answers
table, you can see the answer
column is in an encrypted format.
answers
id user_id question_id answer
--- ------- ----------- -------------------------------------------------
1 1 60 eyJpdiI6Ik12TUMyMkZJT2lOdXEzTmJ6dzBKZFE9PSIsInZhbH
2 1 140 eyJpdiI6IjR4SjdHL3NmMzJTWVZFbjlwQmVZTGc9PSIsIn
3 1 1490 eyJpdiI6InkrYWNCTFJpK29XanhTMzhpS0JnN2c9PSIsIn
4 1 1500 eyJpdiI6IkdvRFhhRklVQldXNnNHYUZWWjliOXc9PSIsIn
5 1 1520 eyJpdiI6Ik93a0wxcHIzYkNMQUJxTEJUMzlUN0E9PSIsIn
02 How To Define Mutators
To define the Mutators, we need to add a method in the relevant model. Let’s say, we have an Answer.php
model and we want to save all the answers into the database in an encrypted format then we can easily do that by creating Mutators in our model.
To do that we need to define a Mutator method with set{Attribute}Attribute
in your model where {Attribute}
is the “studly” cased name of the column you wish to access. In our case, we need to set the encrypted answer so our {Attribute}
will be Answer
as per the “studly” case.
So our method name will be getAnswerAttribute()
as per our example. Moreover, if we want to set the full URL of any image or document on path_name
the database column then your method name will be setPathNameAttribute()
. Let’s now add the method to our model.
03 Example Of Mutators In Laravel
app/Models/Answer.php
<?php
namespace App\Models;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Model;
class Answer extends Model
{
protected $fillable = [
'user_id', 'question_id', 'answer'
];
public function setAnswerAttribute($value)
{
$this->attributes['answer'] = Crypt::encrypt($value);
}
}
You can see in the above example, by using the $this->attributes
you can access any column of your model and you can transform it as you like by using Laravel Mutators.
Now, you can set the encrypted answer as below:
<?php
namespace App\Http\Controllers;
use App\Models\Answer;
class AnswerController extends Controller
{
public function store(Request $request)
{
$userId = Auth::user()->id;
Answer::Create([
'user_id' => $userId,
'question_id' => $request->question_id,
'answer' => $request->answer,
]);
}
}
Once, the above example is executed, then the newly created record will be stored with the encrypted data.
Another Example:
You can also transform the first_name
with the first upper case character simply by defining setFirstNameAttribute()
in the User.php
model. Isn’t it cool?
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = ucfirst($value);
}
}
If you are creating Mutators for any of the existing columns of the database table then you can pass the parameter and transform it as you like or you can also use the $this->attributes['column']
variable.
That’s it from our end. We hope this article helped you to understand what is Laravel Mutators, how to define Laravel Mutators with examples.
Additionally, read our guide:
- Laravel: Pivot Table With An Example
- Laravel: Accessor With An Example
- Laravel: Change Column Type In Migration
- Laravel: Change Column Name In Migration
- How To Use Where Date Between In Laravel
- How To Add Laravel Next Prev Pagination
- Laravel Remove Column From Table In Migration
- Laravel: Get Month Name From Date
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Calculate Age From Birthdate
- How To Dynamic iFrame URL In Elementor
- How To Handle Failed Jobs In Laravel
- How To Remove WooCommerce Data After Uninstall
- How To Get Latest Records In Laravel
- How To Break Nested Loops In PHP Or Laravel
- How To Pass Laravel URL Parameter
- Laravel Run Specific Migration
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!