0
votes

I have a Laravel model with a simple function in it. But for some reason I get this error:

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

Here is my Model:

class Dish extends Model
{
    public function sum() {
        return $this->attributes['begin'] + 10;  
    }
}

In my controller I do:

$model->sum();

Anyone knows how I can add the function to my model?

Many thanks in advance!

1
where does $this point to? - Frank Lucas
Are you sure that error is for that line of code? - Can Vural
Are you trying to load this as a relationship ? Like $model = Dish::with('sum')->where('id', 3)->first(); or something ? - SimonDepelchin
Instead of $this->attributes['begin'] + 10, could you just do $this->begin + 10? Not sure why that would be a problem, but it's a hunch. Laravel thinks it's getting an eloquent relationship here, see Simon's comment above. - Captain Hypertext
Could you show your entire relevant controller code? Nothing wrong with your function or with your call. Sure that the error stack is pointing to this line? - Elias Soares

1 Answers

1
votes

If the calculation will be performed with the model data, you do not need to use $this->attributes to get the model data, that way it actually makes it a bit more "dirty". the cleanest way it will be as mention in the comments:

public function sumBegin($default = 10)
{
    return $this->begin + $default;
}

that way we take the begin for the current model being called.