Laravel 8 - Accessors and Mutators (Eloquent in 2 Steps)
Tags: laravel, php, beginners, bestpractices
Published: 2022-03-04 09:14:09


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/by3xxveez01cib7i7qrz.gif)

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

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();
    }
}
```
also a `route` that looks like this:

**web.php**
```
Route::get('product', [ProductController::class, 'setProduct']);
```

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

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

## Check the result

Go to URL: http://127.0.0.1/product

The result should look something like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xn9bt8r4a2h6grnkw5za.png)
 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jibci6g8d4cwv1ysla4k.gif)

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

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

Open `web.php` and add this route into it.

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

```

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r5pdqm5om0je2gv2eobd.gif)