How to find average and count in Laravel ? Tips

t9

T9

Posted on June 5, 2022

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.

💖 💪 🙅 🚩
t9
T9

Posted on June 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related