Here is the simple laravel’s eloquent code snippet to get results in a table when there are no results for the relationship.
I have two tables called users and accounts. each account belong to one user ,some users not belong to any account they are just users, they can only view the stuff which is posted by accounts/users.
By using “doesntHave” method I am getting the account user data as shown in the below two examples.
Simple query
User::doesntHave('Account')->get();
Above operation will produce the following query SELECT * FROM users WHERE ((SELECT count(*) FROM accounts WHERE user.account_id = accounts.id) < 1)
complex query with optional where condition(s).
$id = 1; User::whereDoesntHave('Account', function ($query) use($id) { $query->where(['id' => $id]); })->get();
Above operation will produce the following query SELECT * FROM users WHERE ((SELECT count(*) FROM accounts WHERE user.account_id = accounts.id and id = 1) < 1)
.