What’s the simplest way to make an IS NULL with Eloquent?

Asked

Viewed 13,822 times

10

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

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

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

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

With the Eloquent, there is some method (not to be highlighted above) that I can make a where making the condition IS NULL or IS NOT NULL?

I believe that this current way ends up being repetitive.

  • I’m reading on the internet about Eloquent and Fluent. But sometimes I come across situations I need to use Fluent.

  • It’s the same thing except that in Fluent you start the query with DB::table instead of Model

  • Personally, I hate fluent. For me, who program in Laravel should use the Model, which is the abstraction, where you can configure the relationships and the like. Fluent no longer does this, he is to make queries more "raw", as is done in Codeigniter

  • Yes. I also don’t like to use Fluent.

1 answer

28


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

follow the examples:

To IS NULL you can use

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

You can also do it in a way, where you can spend several IS NULL more simply:

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

and to NOT NULL

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

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

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

The exit will be:

SELECT * FROM remessas where (campo IS NULL)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.