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('products.id', '=', 'page-visits.visitable_id');
})->get();
$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).

Answers:

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')
            ->join('page-visits','products.id','=','page-visits.visitable_id')
            ->select(DB::raw('count(visitable_id) as count'),'products.*')
            ->groupBy('id')
            ->orderBy('count','desc')
            ->take(10)
            ->get();

I hope you will understand.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x