Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent with Trashed on relationship

Tags:

I need to be able to get a Models Relationship including its soft deleted elements, but only for this 1 instance. I do not want to change the model so that every time I use the relationship it returns all the soft deleted records too.

How can I achieve this?

User Model

class User extends Authenticatable {   public function contacts(){     return $this->hasMany('App\Contacts','user_id','id');   } } 

Controller

$user = User::findOrFail($id); //Need to be able to get the trashed contacts too, but only for this instance and in this function $user->contacts->withTrashed(); //Something like this return $user; 

How can I get the trashed rows only this 1 time inside my controller?

Thanks

like image 518
S_R Avatar asked Aug 02 '18 13:08

S_R


People also ask

What is with trashed 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.

How do I delete a relationship in Laravel?

To delete a model directly, call delete() on it and don't define a deleting listener in its boot method or define an empty deleting method. If you want to further delete relations of a related model, you will define a deleting listener in the boot method of that model and delete the relations there.


1 Answers

You can use withTrashed method in different ways.

To associate the call with your relationship you can do as follows:

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

To use the same in the fly:

$user->roles()->withTrashed()->get(); 

For your special scenario:

$user->contacts()->withTrashed()->get(); 
like image 57
Pusparaj Avatar answered Sep 19 '22 10:09

Pusparaj