Laravel Eloquent OR WHERE IS NOT NULL

Anonymous picture Anonymous · Oct 13, 2014 · Viewed 45k times · Source

I am using the Laravel Administrator package from frozennode. Long story short, I'm running into issues when displaying results that are soft-deleted. I'm trying to override the default query:

select * from `scripts` where `scripts`.`deleted_at` is null group by `scripts`.`id`

To display both deleted results and non-deleted, somehow hacking away. It's not the most elegant solution but I don't see any other way to do it. So, my goal is to do this:

select * from `scripts` where `scripts`.`deleted_at` is null or `scripts`.`deleted_at` is not null group by `scripts`.`id`

Unfortunately I don't know how to use orWhere() with 'is not null'. After researching a bit, I tried it with a raw SQL block, like this:

'query_filter'=> function($query) {
    $query->orWhere(DB::raw('`scripts`.`deleted_at` is not null'));
},

But I ended up with an extra piece of SQL resulting of not including the second parameter in orWhere():

select * from `scripts` where `scripts`.`deleted_at` is null or `scripts`.`deleted_at` is not null **is null** group by `scripts`.`id`

How can I fix this?

Answer

Jeff Lambert picture Jeff Lambert · Oct 13, 2014

Just add withTrashed:

'query_filter'=> function($query) {
    $query->withTrashed();
},

Source

Update

In that case, you can probably just add a orWhereNotNull() call:

'query_filter'=> function($query) {
    $query->orWhereNotNull('deleted_at');
},