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

abingpj's avatar

Laravel raw query to Eloquent.

Hi,

I have a query that I want to convert it into eloquent.

\DB::select('select * FROM brands WHERE id in ( select brand_id from products WHERE category_id IN (220, 222, 223) GROUP by brand_id )');

Any tips?

1 like
1 reply
tisuchi's avatar
tisuchi
Best Answer
Level 70

@abingpj

Brand::whereIn('id', function ($query) {
    $query
        ->select('brand_id')
        ->from('products')
        ->whereIn('category_id', [220, 222, 223])
        ->groupBy('brand_id');
})->get();

Assuming you've already prepped Brand and Product models, you can specify closure to include subquery inside your WHERE IN clause like above.

3 likes

Please or to participate in this conversation.