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!
Try this: $query = Model::where('field1', 1) ->whereNull('field2') ->where(function ($query) { $query->where('datefield', '<', $date) ->orWhereNull('datefield'); } );
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 .
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With