I have something like this:
$items = Item::whereIn("name", $request["names"])->get();
Now I want to get a list of shops that have any of those items. Something like this:
$shops = Shop::whereIn("item_id", $items)->get();
This does not work, because items is an eloquent collection (obviously). I could do some loop and get all the ids like this:
foreach ($items as $item){
$itemIds[] = $item
}
And then use it, but I feel there must be a cleaner way.
Any help?
CodePudding user response:
Use ->pluck('id')
and whereIn()
:
$items = Item::where('name', $request['names'])->get();
$shops = Shop::whereIn('item_id', $items->pluck('id'))->get();
Eloquent Collections have access to many of the same functions of Laravel's Collection Class:
https://laravel.com/docs/9.x/collections#available-methods
->pluck('id')
will return an array of all items.id
records, which you can then use to query via ->whereIn('item_id', ...);