S
S
Sergey delphinpro2021-12-04 14:12:34
Laravel
Sergey delphinpro, 2021-12-04 14:12:34

How to load relationships along with deleted records?

There are two models with a one-to-many relationship

class Bonus {
  function reward(): BelongsTo {
    return $this->belongsTo(Reward::class);
  }
  function user(): BelongsTo {
   return $this->belongsTo(User::class);
  }
}

class Reward {
  function bonuses(): HasMany {
    return $this->hasMany(Bonus::class);
  }
}


And the Bonus model itself is tied to the user with the same attitude.

class User {
  function bonuses(): HasMany {
    return $this->hasMany(Bonus::class);
  }
}


Reward uses "soft" deletion (SoftDeletes).

I am getting a list of bonuses along with their types to display in the admin interface.

$entries = $user->bonuses()->orderBy(...)
  ->with('reward')
  ->paginate();


The Bonus model internally uses a call to Reward. For example, like this:

public function getNameAttribute(): string {
  return $this->reward->localizedAttribute('name');
}


Now, if I remove some reward, then I get an error

Call to a member function localizedAttribute() on null


Basically, it's logical. The deleted model did not load. But in fact it is in the database, just marked deleted.

So I need the remote models to be pulled up and displayed here too.

I looked at the documentation, there is very scarce information on soft removal.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
inFureal, 2021-12-04
@delphinpro

public function roles() {
    return $this->hasMany(Role::class)->withTrashed();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question