What is the simplest way to do an IS NULL with Eloquent?

5

I saw tutorials on the internet that the way you had to make a IS NULL is as follows:

Remessa::where('campo', 'IS', DB::raw('NULL'))->get();

But I was wondering about this, because if an ORM is usually developed thinking of creating a way to query data that is compatible with all DBMS.

Although it works, I believe the form highlighted above is not essential.

With Eloquent , is there any method (without being highlighted above) that I can make a where by doing the condition IS NULL or IS NOT NULL ?

I think this current way ends up getting repetitive.

    
asked by anonymous 04.05.2016 / 17:37

1 answer

9

Yes, there are two methods; one that you can use for IS NULL and another for NOT NULL .

follow the examples:

For IS NULL you can use

Remessa::whereNull('campo')->get();

You can also do this in a way, where you can easily pass several IS NULL :

  Remessa::where(['campo' => NULL, 'usuario_id' => NULL])->get();

and for NOT NULL

Remessa::whereNotNull('campo')->get(); 

To see the results that are generated by the queries, you can use the toSql method at the end to test.

 Remessa::where(['campo' => NULL])->toSql();

The output will be:

SELECT * FROM remessas where (campo IS NULL)
    
05.05.2016 / 14:07