What Is The Use Of Accessor In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Accessors allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. In addition to custom accessors, Eloquent can also automatically cast date fields to Carbon instances or even cast text fields to JSON.

What Is The Use Of Accessor In Laravel With Example

Defining An Accessor

To define an accessor, create a getFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access. In this example, we'll define an accessor for the name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the name attribute:

Open User.php model file and implement code as below

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getNameAttribute($value)//get the only name from user table 
    {
        return ucfirst($value);
    }
}


As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may access the name attribute on a model instance:

So, for example, if we attempt to get the name attribute to Kiran:


Create Route in Web.php file as below

Route::get('/accessors ', 'demoController@accessors')->name('accessors');


Create demoController and implement code to get the name 

php artisan make:controller demoController -mcr


Open demoController.php in app\Http\Controller folder and implement code as below

public function accessors()
    {
        $User =User::find(1);
        dd($User->name);
    }


You may also use accessors to return new, computed values from existing attributes:

public function getFullNameAttribute()
{
return "{$this->name}";
}

If you would like these computed values to be added to the array / JSON representations of your model, you will need to append them.

Related Post