Moose Moose - 1 month ago 10
PHP Question

Laravel Eloquent Query with Specific softDeleted() Records

I'm building an api with Laravel 5.3, which I need to expose some user records. I have no problem getting all the the following:

User::all();

User::all()->withTrashed()->where('status_id', 2);


But how would I combine these to show all regular users + deleted users, but only if the deleted users have a status_id = 2?

all users + deleted users with status_id of 2


To add additional clarification, I'm essentially trying to combine the following queries:

User::all() + User::onlyTrashed->where('status_id', 2);


Thanks for any help!

Answer

Try:

User::all()->withTrashed()
    ->whereNull('deleted_at')
    ->orWhere(function($query) {
        return $query->whereNull('deleted_at')->where('status_id', 2);
    })
    ->get();