The below solution is tested on LARAVEL 9. Solution is to add to the App\Providers\AppServiceProvider this piece of code:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
///...
Builder::macro('whereNullOrEmpty', function ($field) {
return $this->where(function ($query) use ($field) {
return $query->where($field, '=', null)->orWhere($field, '=', '');
});
});
Builder::macro('whereNotNullOrEmpty', function ($field) {
return $this->where(function ($query) use ($field) {
return $query->where($field, '<>', null)->where($field, '<>', '');
});
});
}
//...
}
and then call it like this:
if($nullOrEmpty){
$builder->whereNullOrEmpty('col');
}else{
$builder->whereNotNullOrEmpty('col');
}
You must call both commands:
where($field, '<>', null);
where($field, '<>', '');
because the MySql is handling empty strings and nulls different than a PHP
you also need to wrap those two commands with the closure to tell Eloquent to put generated code in parentheses and isolate MySql code:
(where col = null or where col = '')