Search code examples
phplaravelrating

Laravel Model - Calculate avg ratings


I have table "Orders" where rating score is stored, and inside that table i have relation with places.

I need to grab order rating from each place and calculate the average rating score. I need it on model so I can grab it for later use.

This is the scheme:

[ORDERS]

--order_id = 10

--place_id = 2

--rating = 3

[PLACES]

--place_id = 2

So, when i call: $place->avgRating(),it needs to return 4.3 for example. Pulling the order information is working. Here is the code:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Place extends Model
{
    public function user(){
      return $this->belongsTo('App\User');
    }

    public function orders(){
      return $this->hasMany('App\Order');
    }



}

Solution

  • Have you taken a look at the collection methods in the documentation.

    So add a method in your Place model:

    public function avgRating()
    {
        return $this->orders->avg('rating');
    }
    

    Calling $project->avgRating(); should return what you expect.