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

devkon98's avatar

How to use whereIn with Join eloquent query

Hello i have this query but its not working:

$hasBorrowedCars = CarBorrow::query()
            ->where('borrowed_from_user_id', $userId)
            ->whereIn('car_owners.user_id as owner_id')
            ->join('car_owners','user_id','car_owners.user_id')
            ->exists();
0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The whereIn method should be called on the query builder instance, not on a column name. Here's the corrected query:

$hasBorrowedCars = CarBorrow::query()
    ->where('borrowed_from_user_id', $userId)
    ->join('car_owners', 'car_borrows.car_id', '=', 'car_owners.car_id')
    ->whereIn('car_owners.user_id', [$userId])
    ->exists();

This query will join the car_owners table on the car_id column, and then filter the results to only include rows where the user_id column is equal to $userId. The whereIn method is used to specify the list of user IDs to match against.

Note that I also added the car_borrows.car_id column to the join condition, assuming that this is the column that links the car_borrows and car_owners tables. If this is not the case, you'll need to adjust the join condition accordingly.

1 like

Please or to participate in this conversation.