Using withTrashed with Relationships in Eloquent

Is there a way to use withTrashed with relationships in Eloquent.

I need this. I have a table and a Mark model, and another User table. User has a lot of Mark and Mark belongs to User . Therefore, I defined this in Eloquent models.

Now I need to get a Mark instance that will be deleted. This is not a problem if User not a soft deletion, but if both Mark and User gently removed, I get a Trying to get property of non-object error because

 $mark->user 

will not return the actual user because it will be deleted.

Is there a way I can do something like

 $mark->withTrashed()->user 

to get the associated user even if he is deleted?

+6
source share
2 answers

Depending on your needs, you can determine 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); 

And in your inserted example, this would be:

 $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 
+19
source

You can do it like this:

 $mark->withTrashed()->first()->user->withTrashed()->first() 
+3
source

Source: https://habr.com/ru/post/975350/


All Articles