DEV Community

Cover image for How to find average and count in Laravel ? Tips
T9
T9

Posted on

How to find average and count in Laravel ? Tips

I added a comment Model in my application, and it has a rating and comments section. However, I wanted to display the average rating of a company and the number of comments for that company in the index page.

Here is how I did it, using Eloquent functions withAvg and withCount:

Http\Contollers\CompanyController.php

public function index()
    {
        $company = company::withAvg('rating as ratings', 'rating')->withCount('comment as comments')->latest()->filter()->paginate(12);
         return view('Company.Record.index', compact('company'));

    }
Enter fullscreen mode Exit fullscreen mode

I hope it's useful.

Top comments (0)