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

devkon98's avatar

How to use orWhere in eloquent query

Hello i have this query but makes error:

$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
Level 58

The error in the query is because the orWhere method is being used before the join method. To fix this, move the orWhere method after the join method. Here's the corrected query:

$contactBorrowedThisCar = CarBorrow::query()
    ->where('borrowed_from_user_id', $userId)
    ->join('car_owners', 'user_id', '=', 'car_owners.user_id')
    ->orWhere('car_owners.user_id', $userId)
    ->where('borrowed_to_user_id', $contactId)
    ->where('car_id', $carId)
    ->first();

This query will return the first record that matches the conditions.

Please or to participate in this conversation.