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

Reaper's avatar

Laravel query builder with multiple sub queries

I have these two queries,

$data = Room::whereNotIN('id', function($query) use($request) {
    $query->select('room_id')
        ->from('locks')
        ->where('created_at', '>', Carbon::now()->subMinutes(15));
    })
->get();
$data = Room::whereNotIN('id', function($query) use($request) {
    $query->select('room_id')
        ->from('bookings')
        ->where ('checkout_date', '>=', $request->checkin_date)
        ->where('checkin_date', '<=', $request->checkout_date);
    })
->get();

But I want these subqueries in a single query This is what I've tried but is not working,

$data = Room::whereNotIN('id')
    ->select('room_id')                            
    ->selectSub(function($query) {
    $query->from('locks')
        ->where('created_at', '>', Carbon::now()->subMinutes(15));
    })
    ->selectSub(function($query) use($request) {
    $query->from('bookings')
        ->where ('checkout_date', '>=', $request->checkin_date)
        ->where('checkin_date', '<=', $request->checkout_date);
    })
    ->get();
0 likes
1 reply
SilenceBringer's avatar
Level 55

@reaper

Room::whereNotIn('id')

missing second attribute.

What's the problem to just combine 2 previous queries?

$data = Room::whereNotIn('id', function($query) use($request) {
    $query->select('room_id')
        ->from('locks')
        ->where('created_at', '>', Carbon::now()->subMinutes(15));
})
	->whereNotIn('id', function($query) use($request) {
    	$query->select('room_id')
        	->from('bookings')
        	->where ('checkout_date', '>=', $request->checkin_date)
        	->where('checkin_date', '<=', $request->checkout_date);
    })
->get();
1 like

Please or to participate in this conversation.