DEV Community

loading...
Cover image for Accessors in Laravel - quick view with example

Accessors in Laravel - quick view with example

mmj profile image MMJ ・2 min read

First thing first: what’s an accessor?
An accessor is a custom method we can create inside a model and that can get and manipulate an attribute of that model. Its result can be a new attribute of that model or “substitute” an existing one.

Real case scenario: for instance, if we have a model mapping to an “album” table that has a “thumb” field in which the name of its thumbnail is stored. When we retrieve that value and put it in the src of a img tag, it can be annoying to build the path and then print that value at the end, especially if we have a lot of images.

We can build our accessor that creates a new attribute of that model and that will return the complete url for us. The name of the method must be built in this way: get{Name}Attribute. The “Name” can be what you want but if you use the name of the album’s field you are retrieving, the value of the field will be automatically passed.
So, in the album model we can write:

    public function getPathAttribute(){
        return 'pathToThumbsFolder/'.$this->thumb;
    }
Enter fullscreen mode Exit fullscreen mode

Or using the field name

    public function getThumbAttribute($value){
        return 'pathToThumbsFolder/'.$value;
    }
Enter fullscreen mode Exit fullscreen mode

When we have an instance of an album, this accessor will let us write

$album->thumb
Enter fullscreen mode Exit fullscreen mode

Where we want to get or print the full url to the thumbnail.
Of course, we can set that path in the .env file and use something like env('ALBUM_THUMB_DIR') as path in this method.

Further example: it can help building an if statement to show a default image if album has no thumbnail make the html code cleaner.

    public function getThumbAttribute($value){
        return $value?'pathToThumbsFolder/'.$value:'pathToDefaultImage/default.jpg';
   }
Enter fullscreen mode Exit fullscreen mode

This can be very helpful, save a lot of code and make it cleaner because every time you need to retrieve a value manipulating it first you have only one place to do it and possibly change it later.

Discussion (0)

pic
Editor guide