Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using withTrashed with relationships in Eloquent

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?

like image 735
Vuk Stanković Avatar asked Sep 16 '14 11:09

Vuk Stanković


People also ask

What does withTrashed do in Laravel?

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.


1 Answers

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 
like image 68
Jarek Tkaczyk Avatar answered Sep 23 '22 11:09

Jarek Tkaczyk