DEV Community

DaleLanto
DaleLanto

Posted on

Laravel 8 - Accessors and Mutators (Eloquent in 2 Steps)

Laravel Accessors and Mutators are custom, user defined methods. Accessors are used to format the attributes when you retrieve them from database. Whereas, Mutators are used to format the attributes before saving them into the database.

Lets' Start Creating and Using Accessor and Mutators!

Image description

Suppose that you have a Model that looks like this:

app/Product.php



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


Enter fullscreen mode Exit fullscreen mode

and a Controller that looks like this:

ProductController.php



<?php

namespace App\Http\Controllers;

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

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

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

        $product->save();
    }
}


Enter fullscreen mode Exit fullscreen mode

also a route that looks like this:

web.php



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


Enter fullscreen mode Exit fullscreen mode

Step 1: Create Mutators In The Model

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.

Paste this in app/Product.php



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


Enter fullscreen mode Exit fullscreen mode

It should now look like this:



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


Enter fullscreen mode Exit fullscreen mode

Check the result

Go to URL: http://127.0.0.1/product

The result should look something like this:
Image description

Image description

Step 2: Create Accessors In The Model

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.

Open Product.php and add this code into it



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


Enter fullscreen mode Exit fullscreen mode

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



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

        foreach ($products as $product) {

            echo $product->name . "<br/>";
        }
    }


Enter fullscreen mode Exit fullscreen mode

Open web.php and add this route into it.



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

Enter fullscreen mode Exit fullscreen mode




Check the Result

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.

Hurray! We have successfully created and used accessors and mutators , use this on your future projects to improve the readability , stability and performance of your code!

Image description

Top comments (1)

Collapse
 
wahbibaklouti7 profile image
Wahbi Baklouti

Thank you,
I have a question. It's possible to create a custom accessor and mutator.
Example: if i want to get the full name of the use and i don't have a column with this name?