How to calculate the average in Eager Loading Laravel?

You might have heard of the term Lazy Loading. Eager Loading works the opposite of it. Eager Loading makes you get all the required data at the same time. We can calculate the average value for a database column using the eager loading in Laravel. Consider the code snippet below that helps explain this concept in Laravel.

public function reviewRows()
{
    return $this->hasManyThrough('ReviewRow', 'Review');
}

public function avgRating()
{
    return $this->reviewRows()
      ->selectRaw('avg(rating) as aggregate, product_id')
      ->groupBy('product_id');
}

public function getAvgRatingAttribute()
{
    if ( ! array_key_exists('avgRating', $this->relations)) {
       $this->load('avgRating');
    }

    $relation = $this->getRelation('avgRating')->first();

    return ($relation) ? $relation->aggregate : null;
}

The reviewRows() function returns. the number of rows that have the mentioned class name.

Leave a Comment