Eloquent Mutators and Accessors in Laravel 9 Tutorial

Reading Time: 7 minutes
4,276 Views

In Laravel, mutators and accessors allow us to alter data before it’s saved to and fetched from a database. To be more specific, the mutator allows us to alter data before it’s saved to a database. On the other hand, the accessor allows us to alter data after it’s fetched from a database.

In this article, we will see Eloquent mutators and accessors in Laravel 9. We will consider an example and will understand in detail. This is a very useful guide which makes you understand about Eloquent ORM mutators and accessors.

We work with the concept of mutators and accessors methods into the Laravel model which is the central place of application.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Migration

Open project into terminal and run this command to create migration file.

$ php artisan make:migration create_products_table

It will create 2022_04_17_031027_create_products_table.php file inside /database/migrations folder. Open migration file and write this following code into it.

The code is all about for the schema of products table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('amount');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};

Run Migration

Back to terminal and run this command.

$ php artisan migrate

It will create products table inside database.

About Laravel Mutators

A mutator transforms an Eloquent attribute value when it is set. Mutators work when we save data inside database table.

Syntax to create mutators –

To define a mutator, define a set{Attribute}Attribute method on your model where {Attribute} is the “studly” cased name of the column which we want to get altered when saved.

Create Model with Mutator

Back to project terminal and run this command to create model.

$ php artisan make:model Product

It will create Product.php file inside /app/Models folder.

Open Product.php and write this complete code into it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'amount', 'description'
    ];

    // Mutator for Name column
    // when "name" will save, it will convert into lowercase
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = strtolower($value);
    }
}
  • Mutator – setNameAttribute($value)
  • It will alter value then assign to $this->attributes[‘name’]
  • Other names mutator as – column name ( created_at ) -> setCreatedAtAttribute()

Concept

public function setNameAttribute($value)
{
    $this->attributes['name'] = strtolower($value);
}

Note*: To create a model and migration using single command you can use this too.

$ php artisan make:model Product -m

-m for Migration

Next,

Mutator Usage in controller

Open project terminal and run this command.

$ php artisan make:controller ProductController

It will create ProductController.php inside /app/Http/Controllers folder.

Open ProductController.php file and write this code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    public function index()
    {
        $product = new Product();

        $product->name = "Sample Product 1";
        $product->amount = 12;
        $product->description = "Sample product created";

        $product->save();
    }
}

Inside this above code we are only creating a sample product and save.

Once you save the data you will see in your database inside products table, product name will be in lowercase. If you pass any value, mutator will covert name value to lowercase and then save to database table.

About Laravel Accessors

An accessor transforms an Eloquent attribute value when it is accessed. It works when we fetch data from table.

Syntax to create accessor –

To define an accessor, create a get{Attribute}Attribute method on your model where {Attribute} is the “studly” cased name of the column.

Let’s create a accessor inside model.

Update Model with Accessor

Open Product.php and add this code into it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'amount', 'description'
    ];

    // Accessor for Name column
    // when "name" will accessed, it will convert into uppercase
    public function getNameAttribute($value)
    {
        return strtoupper($value);
    }
}

Concept

public function getNameAttribute($value)
{
    return strtoupper($value);
}

Accessor Usage in Controller

Open ProductController.php controller file and add this method into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    //...

    public function getProducts()
    {
        $products = Product::get();

        foreach ($products as $product) {
            
            echo $product->name . "<br/>";
        }
    }
}

Inside this above code we are only fetching the database rows from products table.

Once you get data and print into your output screen you will see Product name will be in uppercase. This is because of data accessor. At runtime accessor will manipulate the value of which they created.

Mutators – Special methods of model which alters the data before save to database.

Accessors – Special methods of model which alters the data before output from database.

We hope this article helped you to learn about Eloquent Mutators and Accessors in Laravel 9 Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.