How to get records from a table when there is no relationship with another table in Laravel?

Question:

In Laravel, when I want to get data from a table that contains some relationship, or when I want to get data from a condition of a related table, for example, usuarios that contain livros , I use the has or whereHas method.

So:

 Usuario::has('livros')->get();

Or like this:

 Usuario::whereHas('livros', function ($query)
 {
      $query->where('titulo', '=', 'Harry Potter');
 })->get();

But now I need the reverse situation.

I only want to capture users who do not have relationships with Livros .

I only want to capture users who don't have relationships with Harry Potter books.

How can I do this on Laravel?

Answer:

Since no one has responded, I will.

Just use the doesntHave and whereDoesntHave methods.

For example, I want all usuários that don't have the 'admin' nível , both of which have an N:N .

$usuarios = Usuario::whereDoesntHave('niveis', function ($query)
{
     $query->where('nome', '=', 'admin');

})->get();

If I now only want users who have no relationship with niveis then we can simply use doesnHave

  Usuario::doesntHave('niveis')->get();

In that answer in English , there are also some examples that I put there.

Scroll to Top