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

Ligonsker's avatar

take() for each unique id

Hello, If I have the following query:

Table::whereIn('id', $ids_arr)->get();

Is it possible to use something like take(5) but for each unique id?

Thanks

0 likes
6 replies
Ligonsker's avatar

@Sinnbeck You are correct, I have a typo in my post which is confusing - This is a second table with ids as foreign keys so it should've been:

Table2::whereIn('table_1_id', $ids_arr)->get();
Sinnbeck's avatar

@Ligonsker Ok then try

Table2::select('table_1_id')->whereIn('table_1_id', $ids_arr)->groupBy('table_1_id')->limit(5)->get();

Or

Table2::distinct('table_1_id')->whereIn('table_1_id', $ids_arr)->limit(5)->get();
1 like
Ligonsker's avatar

@Sinnbeck The problem with this, is that it always gives 5 results, but not 5 from each

Please or to participate in this conversation.