Laravel, “withTrashed()” linking a deleted relationship
1 min readMay 27, 2020
We have DB table posts, which is linked to table users with a field posts.user_id = users.id.
class User extends Model {
use SoftDeletes; ......}
With Eloquent we can define the relation easily.
class Post extends Model {
public function user() {
return $this->belongsTo('App\User');
}
}
If the user gets deleted, and on the User model we use the SoftDeletes trait, you can use withTrashed() method here.
class Post extends Model {
public function user() {
return $this->belongsTo('App\User')->withTrashed();
}
}
then just $post->user
or just simple use the relationship method to return the user
$post->user()->withTrashed()->get()
$post->user()->withTrashed()->first()