Ad

Eloquent Model Method Or Attribute For Calculation

- 1 answer

I'm looking for a way to define a custom Eloquent method which only returns a calculation based on several columns in the according database table. I also tried setting it in the models attributes, but neither seem to work. Maybe I'm missing something, here's what I got so far:

<?php

use Illuminate\Database\Eloquent\Model;

class Team extends Model
{
    public function difference() {
        return $this->goals_f - $this->goals_a;
    }
}

The error message I'm recieving is:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
Ad

Answer

Your error makes it sound to me like you are trying to call your method like a property" $team->difference. You would instead need to call it like: $team->difference(). If you want to get the difference as if it was a property, then you would need to define an accessor:

public function getDifferenceAttribute(){
    return $this->goals_f - $this->goals_a;
}

Then you could call it like $team->difference.

You could also define a protected $appends property to your model so that the difference property is subsequently visible in it's JSON representation:

protected $appends = ['difference'];

More information: https://laravel.com/docs/5.2/eloquent-mutators#accessors-and-mutators

Ad
source: stackoverflow.com
Ad