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.