Step-by-Step Guide to Using Laravel Accessors

Accessor allows us to transform Eloquent attribute values when we retrieve data. We can use accessors to manipulate, format, and access association fields from the model itself. In this article, we will go through the example of how we can use accessors to manipulate the retrieved data of all cases that are being used in the real world.

Defining accessors to format fields

The accessors in Laravel 8 are defined by creating a method in the model with the convention of get{FieldName}Attribute where we can access it back by calling the model instance $model->field_name. Laravel automatically converts the accessors from the model into snake_case.

In the user model

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $fillable = [
        'firstname',
        'lastname',
        'email',
        'password',
    ];

    public function getNameAttribute()
    {
        return "{$this->firstname} {$this->lastname}";
    }
}

Using an accessors

In the user controllers

<?php

namespace App\Http\Controllers;

use App\Models\User;

class UserController extends Controller
{
    public function accessorTest($id)
    {
        $user = User::findOrFail($id);
        return $user->name;
    }
}

Defining accessors to get association fields

Accessors are not only able to format and manipulate data of their own fields we also can take advantage of it by using them to get and manipulate the data of it association model.

In the user model

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $fillable = [
        'firstname',
        'lastname',
        'email',
        'password',
        'org_id'
    ];

    public function getNameAttribute($value)
    {
        return "{$this->firstname} {$this->lastname}";
    }

    public function organization()
    {
        return $this->belongsTo(Organization::class);
    }

    public function getOrganizationNameAttribute()
    {
        return $this->organization ? $this->organization->name : '';
    }

}

Using an accessors

In the user controllers

<?php

namespace App\Http\Controllers;

use App\Models\User;

class UserController extends Controller
{
    public function accessorTest($id)
    {
        $user = User::findOrFail($id);
        return $user->organization_name;
    }
}