Use whereIn with values from a seperate query in Laravel

Viewed 429

I'm having trouble with the whereIn() function.

I have two tables carts and items. Carts stores user IDs and item IDs, while the items table stores item IDs and item information.

What I would like to do is get all items that are in the cart table with in the signed in users ID.

Right now I'm first getting the item ID's matching the active user:

$IDs = Cart::select('item_id')->where('user_id', auth()->id());

Then I want to select all items with an ID in $IDs

$items = Item::all()->whereIn('id', function($query) {
    $query->select('item_id')->from($IDs->item_id);
});

However when I try this, I get the error

Object of class Illuminate\Database\Query\Builder could not be converted to int.

When I replace $IDs with something like [1234, 4321], it works.

How can I fix this problem?

1 Answers
$IDs = Cart::select('item_id')->where('user_id', auth()->id());

this line return a query builder not a collection of ids ...

anyway you can get the ids in array and use it directly for whereIn :

$IDs = Cart::where('user_id', auth()->id())->pluck('item_id')->all();

$items = Item::whereIn('id',$IDs)->get();
Related