Is there a way to use withTrashed
with relationships in Eloquent.
What I need is this. I have table and model Mark
and another table User
. User
has many Mark
and Mark
belongs to User
. So I defined this in Eloquent models.
Now I need to get an instance of Mark
that is soft deleted. This is not a problem if User
isn't soft deleted, but if both Mark
and User
are soft deleted, I get an error Trying to get property of non-object
, because
$mark->user
won't return actual user, cause it is soft deleted.
Is there a way that I can do something like
$mark->withTrashed()->user
to get this related user even if it is deleted?
Laravel, “withTrashed()” linking a deleted relationship With Eloquent we can define the relation easily. If the user gets deleted, and on the User model we use the SoftDeletes trait, you can use withTrashed() method here.
Depending on your needs, you can define the relationship:
public function marks() { return $this->hasMany('Mark')->withTrashed(); } // then just $user->marks;
or use it on the fly:
$user->marks()->withTrashed()->get(); // or when lazy/eager loading $user = User::with(['marks' => function ($q) { $q->withTrashed(); }])->find($userId);
then your case would turn into:
$mark->user() // get relation object first ->withTrashed() // apply withTrashed on the relation query ->first(); // fetch the user // alternatively you use getResults relation method $mark->user() ->withTrashed() ->getResults(); // returns single model for belongsTo $user->marks()->withTrashed() ->getResults(); // returns collection for hasMany
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With