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

Virtualmix's avatar

Query builder whereIn AND whereNotIn

Hello All,

I was hoping to get some help with the following query builder. I would like to return a random listing that exists in my 'quotes' table but does not exists in my 'orders' table.

    $listing = App\Listing::whereIn('id', function ($p) {
        $p->select('listing_id')->from('quotes');
    }, 'AND')
    ->whereNotIn('id', function ($q) {
        $q->select('listing_id')->from('orders');
    })
    ->get()->random();

I've spent hours trying to get this query working... It's close but still returns listings that already exists in the orders table...

Any idea what I'm doing wrong?

0 likes
5 replies
staudenmeir's avatar

Please provide some sample data that produces an incorrect result.

Snapey's avatar
Snapey
Best Answer
Level 122
$orders = Order::pluck('listing_id');
$quotes = Quote:: pluck('listing_id');

$listing::whereIn('id',$quotes)
                ->whereNotIn('id',$orders)
                ->inRandomOrder()
                ->first();
1 like
Virtualmix's avatar

@snapey: Just wanted to thank you for your help with this query. You taught me a new way to fetch data and I now use this snippet in my app. Thanks!

Snapey's avatar

great. Can you mark it as best reply?

Please or to participate in this conversation.