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

devkon98's avatar

Trying to user OrWhere with Join in eloquent query

Hello i have this query that i need to use orWhere but makes error, this is my query:

$contactBorrowedThisCar = CarBorrow::query()
            ->where('borrowed_from_user_id', $userId)
            ->orWhere('car_owners.user_id as owner_id' , $userId)
            ->where('borrowed_to_user_id', $contactId)
            ->where('car_id', $carId)
            ->join('car_owners','user_id','car_owners.user_id')
            ->first();
0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue with the current query is that the orWhere method is being used incorrectly. It should be used to group multiple conditions together, but in this case, it is being used to join a table. To fix this, we can use a subquery to get the car owners with the given user ID, and then use orWhere to group the two conditions together. Here's an example:

$contactBorrowedThisCar = CarBorrow::query()
    ->where(function ($query) use ($userId) {
        $query->where('borrowed_from_user_id', $userId)
            ->orWhereIn('car_id', function ($subquery) use ($userId) {
                $subquery->select('car_id')
                    ->from('car_owners')
                    ->where('user_id', $userId);
            });
    })
    ->where('borrowed_to_user_id', $contactId)
    ->where('car_id', $carId)
    ->first();

In this example, we're using a subquery to get the car IDs for the given user ID, and then using orWhereIn to include those car IDs in the main query. We're also using a closure to group the two conditions together with orWhere.

1 like

Please or to participate in this conversation.