Add an additional field to Laravel model using Laravel Accessors

Published on Apr 6, 2021

There are times in life when you want to add a field to the result of a Laravel model. Luckily for us Laravel has an awesomely simple way to do this.

Introducing Laravel Accessors

Looking at the code below if we want to add a full_name attriute to the model that utilises the first_name and last_name attribute of that model then we can do this

public function getFullNameAttribute()
   {
       return $this->first_name.' '.$this->last_name;  
   }

Appending accessors to Laravel results

You can return this every time with the model by adding it to the appends attribute on the model.

protected $appends = ['totalCost'];

Tagged with: Laravel PHP
Written by Aaron Lumsden