Laravel wherenotexists returning null

I have the following piece of code

 $not_paid = Tenant::where('property_id', $property_id)
            ->whereNotExists(function ($query) use ($property_id) {
                $query->select('user_id')
                ->from('rent_paids'); 
            })
            ->get();

which is supposed to get all the tenants in a certain property, look them up in the rent_paids table and return the users who are not in the rent_paids table, as follows:

tenants table

Iduser_idproperty_id
111
221
331

rent_paids

Iduser_idproperty_idamount_paid
1113000

I want to be able to return the users in the tenants table and not in the rent_paids table. In this case, users 2 and 3. But the above code returns an empty array.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re missing the where clause to tie it back to the original table.

$not_paid = Tenant::where('property_id', $property_id)
        ->whereNotExists(function ($query) use ($property_id) {
            $query->select('user_id')
            ->from('rent_paids')
            ->whereColumn('tenants.user_id', '=', 'rent_paids.user_id'); 
        })
        ->get();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x