0

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!

5
  • where does $this point to? Commented Oct 14, 2016 at 10:42
  • Are you sure that error is for that line of code? Commented Oct 14, 2016 at 10:44
  • Are you trying to load this as a relationship ? Like $model = Dish::with('sum')->where('id', 3)->first(); or something ? Commented Oct 14, 2016 at 10:45
  • 2
    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. Commented Oct 14, 2016 at 12:42
  • 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? Commented Oct 14, 2016 at 13:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.