title: Getting an average in a ratings system in Laravel
body: <p>Currently trying to get an overall average for each of my products based from the reviews. But my code seems to be summing all of the ratings rather than the ones where the reviews are related to the Product. </p>
  
  <p>My tables are:</p>
  
  <p><strong>Products</strong>: id, name, price
  <strong>Reviews</strong>: id, Review, product_id(fk), ratings_id(fk)
  <strong>ratings</strong>: id , rating</p>
  
  <pre><code>class Product extends Model {
  
      public function reviews()
      {
          return $this-&gt;hasMany('App\Review','products_id');
      }
    }
  
  
  
   class Rating extends Model
     {
      //
      public function reviews(){
          $this-&gt;hasMany('App\Review');
      }
     }
  
  class Review extends Model
  {
      //
      public function products(){
          return $this-&gt;belongsTo('App\Product');
      }
  
      public function ratings()
      {
          return $this-&gt;belongsTo('App\Rating');
      }
  
  }
  </code></pre>
  
  <p><strong>ProductsController:</strong> : </p>
  
  <pre><code>   public function getSingle($slug )
      {
          //fetch from the database based on slug.
          $product = Product::where('slug', '=', $slug)-&gt;first();
  
  
          //return view
          return view('products.single')-&gt;withProduct($product);
  
      }
  </code></pre>
  
  <p>then my view and where i encounter the <strong>problem</strong> of retrieving an average of the whole rating column and not just of this product.:</p>
  
  <pre><code>@foreach($product-&gt;reviews as $reviews)
  
  &lt;h4&gt;Rated: {{$reviews-&gt;ratings-&gt;sum('rating') / Count($product-&gt;reviews)}} &lt;/h4&gt;
  @endforeach      
  </code></pre>
  
  <p>Where am i going wrong and why am i not achieving an average of a certain product reviews rating but an average of review ratings for all products.</p>