Home » Php » Eloquent/Query builder Laravel: Select from table A without exists in table B

Eloquent/Query builder Laravel: Select from table A without exists in table B

Posted by: admin October 26, 2017 Leave a comment

Questions:

I have 3 table as below:

User: id, name

Room: id, room_name

User_Room: user_id, room_id

How can I select all user from table User, without user exist in Table Room_User ?

I already followed with this post but I don’t know how to convert query below to Eloquent or Query Building

select A.*
from A left join B on A.BAND = B.HATE
where B.HATE IS NULL;

Please help.

Answers:

If you have a Many to Many relationship between the tow Models then you can simply use whereDoesntHave method (Querying Relationship Absence section) :

$users = User::whereDoesntHave('rooms')->get();