Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

V9द's avatar
Level 3

Create Query with Eloquent

I want to use laravel eloquent to implement the below query. Please help

SELECT COUNT(`category_id`) as categorycount,`category_id`,`product_id` FROM `productcategories` GROUP BY `category_id` ORDER BY categorycount DESC

Model Name is Productcategory

1 like
3 replies
BezhanSalleh's avatar
Productcategory::select(DB::raw('count(category_id) as categoryCount','category_id','product_id')
    ->groubBy('category_id','product_id')
    ->orderBy('categorycount','desc')
    ->get();
1 like
tisuchi's avatar
tisuchi
Best Answer
Level 70

Try this-

App\Productcategory::selectRaw('category_id, product_id, count(*) categorycount')
                            ->orderBy('categorycount', 'desc')
                            ->groupBy('category_id')
                            ->get();
7 likes

Please or to participate in this conversation.