mafortis
mafortis

Reputation: 7128

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).

Upvotes: 0

Views: 550

Answers (1)

Sagar Gautam
Sagar Gautam

Reputation: 9389

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.

Upvotes: 3

Related Questions