Search code examples
laraveleloquent

Select all soft deleted item which owner is not soft delete in Eloquent / Laravel


I have a query to get all soft delete tournaments:

 $tournaments = Tournament::onlyTrashed();

Thing is Tournament model has a FK owner_id.

Sometimes, owner has been soft deleted, so when I try to get $tournament->owner->id, I get an exception.

How to get All trashed Tournament which user is not soft deleted in Eloquent?

Is there a more elegant (Eloquent) solution that :

 $tournaments = Tournament::onlyTrashed()
            ->join('users', 'users.id', '=', 'tournament.user_id')
            ->where('users.deleted_at', '=', null)
            ->select('tournament.*')
            ->get();

Solution

  • has and whereHas (for more complex relationship requirements) can be used to limit results to records that have an active relationship.

    Tournament::has('Owner')
    

    will select only tournaments with a valid (existing and non-soft-deleted) Owner.