Where NOT in pivot table

Submitted by wallacemaxters - 9 years ago

Get results in a table when there are no results for the relationship

// Simple query

User::doesntHave('Role')->get();

//SELECT * FROM users WHERE ((SELECT count(*) FROM roles WHERE user.role_id = roles.id) < 1)

// For complex query

$id = 1;
User::whereDoesntHave('Role', function ($query) use($id) {
      $query->whereId($id);
})
->get();

//SELECT * FROM users WHERE ((SELECT count(*) FROM roles WHERE user.role_id = roles.id and id = 1) < 1)