Eloquent Mutators and Accessors in Laravel 8 Tutorial

Share this Article
Reading Time: 7 minutes
2,557 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.


Installation of Laravel Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project.

If your system doesn’t has composer Installed, Learn Composer Installation Steps.

Here is the complete command to create a laravel project-

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

After following these steps we can install a Laravel application into system.

To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel already installed at 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 aboutEloquent 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.

Find More on Laravel 8 Articles here