How to set a function in a model as an attribute

If you have a model with a function that you want to use it as an attribute, all you have to do is to use protected $appends in the Model class

For example, you have a Project class with a function that gets the sum of all invoices for that project

class Project extends Model
{
protected $appends = ['prev_invoices'];
....
public function getPrevInvoicesAttribute()       
    {
        $sum = Invoice::where('project_id', $this->id)
            
            ->sum('amount');
        return $sum;
    } 

Note that the function name must be formatted like that: “get” at the beginning, “Attribute” at the end, and the name to be CamelCase.

Leave a Reply

Your email address will not be published. Required fields are marked *