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

nevakil's avatar

Query to Eloquent

Hi,

I have this query and want to convert it to Eloquent. Can someone help me?

\DB::select('select * FROM cups WHERE id in ( select cup_id from products WHERE category_id IN (12, 29, 54) GROUP by cup_id )');

0 likes
2 replies
bobbybouwmann's avatar
Level 88

Try this

Cuup::whereIn('id', function ($query) {
    $query->select('cup_id')->from('products')->whereIn('category_id', [12, 29, 54])->groupBy('cup_id');
})->get();

You can also improve this using relationships, but then you need to set them up first.

piljac1's avatar

Two things to note regarding @bobbybouwmann answer.

For the proposed solution to work, you need to have a Cup model. Else, you would have to use \DB::table('cups') instead.

Also, you would probably need to have a dynamic array of IDs in your whereIn clause. If you do, you can achieve it by passing your array variable to the use statement of the anonymous subquery function:

Cup::whereIn('id', function ($query) use ($categoryIds) {
    $query->select('cup_id')->from('products')->whereIn('category_id', $categoryIds)->groupBy('cup_id');
})->get();

P.S. You don't need the use statement with $this, so if you get your category IDs with a function/relation of the current class, you can omit it.

Please or to participate in this conversation.