Diego Ponciano
Diego Ponciano

Reputation: 450

How can I get average from a polymorphic relation in Laravel?

So I have a feedback model as a many to many polymorphic relation, for now I can say:

$user->feedbacks 

and it will retrieve the relation accordingly, now I want to do something like:

$user->feedbacks->getAverage()

to simply spit the average feedback rating (which are numbers from 1 to 5)

I added the following function to my Feedback.php model file:

public function getAverage(){

    $described = $this->avg('described');
    $recommend = $this->avg('recommend');
    $communication = $this->avg('communication');

    $average = ($described + $recommend + $communication) / 3;

    return $average;
}

But Laravel will not recognize this method.

Please help.

Upvotes: 0

Views: 150

Answers (1)

user3010273
user3010273

Reputation: 900

The method should be on the User model. If you look at the chain of objects, you are trying to call the getAverage method on a Collection class instance (that's what querying a Model for related Models will return for you). A collection doesn't have a method named getAverage().

To solve your problem, create the getAverage() method on the User model and inside of it, fetch the related Feedback model collection and compute the average based on the retrieved Models.

Upvotes: 1

Related Questions