Get value with max amount in Laravel

I’m using laravel-page-view-counter to count visits of my products and it’s working just fine, what i need to do is to get list of top 10 products by their visits (get 10 products which has largest number of visits).

Here is what I have:

$visits = Product::join('page-visits', function ($join) {
  $join->on('', '=', 'page-visits.visitable_id');
$sorted = $visits->sortBy(function ($product, $key) {
  return count($product['visits']);

But It return from lowest product visits to highest one (it shows product with 0 visit till product with 100 visits) I need reverse method of that to show (product with 100 visits first).


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can do it easily with query builder and some raw queries like this:

$visits = DB::table('products')
            ->select(DB::raw('count(visitable_id) as count'),'products.*')

I hope you will understand.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x