Eloquent Mutators and Accessors in Laravel 8 Tutorial

Reading Time: 7 minutes
8,487 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 8. 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.

If you want to learn about Laravel 8 Relationships, click on these articles:

Let’s get started.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

composer create-project --prefer-dist laravel/laravel blog

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

Create a migration which creates a products table.

$ php artisan make:migration create_products_table --create=products

After running this command at your terminal, you will see one file will be created at this following path /database/migrations.

Open {timestamp}_create_products_table.php file and write this complete code into it.

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreateProductsTable 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');
    }
}

Now, you have to run this given command to migrate the above file.

$ php artisan migrate

Above command will creates a products table in database.


Create Model

Open terminal and run this artisan command to create model file.

$ php artisan make:model Product

It will create a model file Product.php at /app/Models folder.

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

$ php artisan make:model Product -m

-m for Migration


Create 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.

Let’s create a mutator method in model.

Create Model

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()

Next,

Create controller

$ 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 above code, we are only creating a test product.

Create Route

Open web.php from /routes folder. Add this route into it.

Route::get('product', [ProductController::class, 'index']);

Start development server

URL: http://127.0.0.1/product

Successfully, we can see the name of product altered. Before saving we have in capital format first letter of each word. But we converted into all lower case.


Create 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 method in model.

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);
    }
}

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/>";
        }
    }
}

Open web.php and add this route into it.

Route::get('list-product', [ProductController::class, 'getProducts']);

URL: http://127.0.0.1/list-product

You should see the list of names (name of product) each in uppercase. This is because we have altered value by accessor method.

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

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more