Home » Source Book » Laravel Mutators With An Example

Laravel Mutators With An Example

Last updated on June 14, 2022 by

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:

  1. Laravel: Pivot Table With An Example
  2. Laravel: Accessor With An Example
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How To Dynamic iFrame URL In Elementor
  12. How To Handle Failed Jobs In Laravel
  13. How To Remove WooCommerce Data After Uninstall
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. 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!

Leave a Comment