Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel / Eloquent whereIn with null

How do I apply Laravel's Eloquent whereIn() so that it includes null?

I've tried:

User::whereIn("column", [null, 1, 2]) -> get();

And

User::whereIn("column", [DB::raw("null"), 1, 2]) -> get();

But both queries return no results.

Thanks!

like image 207
John1984 Avatar asked Nov 17 '16 14:11

John1984


People also ask

Where condition is null in laravel?

Try this: $query = Model::where('field1', 1) ->whereNull('field2') ->where(function ($query) { $query->where('datefield', '<', $date) ->orWhereNull('datefield'); } );

Is null in laravel eloquent?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .


2 Answers

I don't think you can pass null in in mysql statement. If you run the query in mysql console it will skip the null.

Try User::whereNull('column')->orWhereIn('column', array(1, 2))->get();

like image 198
Saumini Navaratnam Avatar answered Oct 23 '22 17:10

Saumini Navaratnam


Fetching data with either null and value on where conditions are very tricky. Even if you are using straight Where and OrWhereNotNull condition then for every rows you will fetch both items ignoring other where conditions if applied. For example if you have more where conditions it will mask out those and still return with either null or value items because you used orWhere condition. Just like @Angelin Calu mentioned above in comment section.

The best way so far I found is as follows. This works as where (whereIn Or WhereNotNull).

User::where(function ($query) {
            $query->whereIn('column',[1,2])->orWhereNull('column');                  
        })->get();
like image 39
Deepesh Thapa Avatar answered Oct 23 '22 15:10

Deepesh Thapa