laravel-5.4laravel-4.2

How can I grab the top 10 most occurring values in mysql table column using laravel eloquent?


I want to grab the top 10 most occurring values in mysql table column using laravel 4.2.

For example, the top 10 occurring products and its counts, as in the below raw MySQL query:

SELECT `product_id`, COUNT(*)
FROM `product_details`
GROUP BY `product_id`
ORDER BY COUNT(*) DESC
LIMIT 10;

Solution

  • Try this syntax:

    DB::table('product_details')
            ->select('product_id', DB::raw('COUNT(*) AS cnt'))
            ->groupBy('product_id')
            ->orderByRaw('COUNT(*) DESC')
            ->take(10)
            ->get();