belongsTo() and withTrashed() – linking to deleted row

Let’s say we have DB table products, which is linked to table categories with a field products.category_id = categories.id, Eloquent helps us to define a relation easily. But what if the category gets (soft) deleted, but we still need to have that relationship to be returned for history reasons? You can use withTrashed() method here.

Here’s what exactly I mean. Model Product.php should look like this:

// ...

class Product extends Model {

	public function category() {
		return $this->belongsTo('App\Category');
	}

}

And then we can use that relationship in viewing the data, like this:

{!! $product->category->title !!}

But, getting back to the situation: if the category gets Soft Deleted (i.e. field deleted_at is not null), then that row wouldn’t be returned with query. But you can simply add withTrashed() in the model itself, like this:

public function category() {
	return $this->belongsTo('App\Category')->withTrashed();
}
Like our articles?
Check out our Laravel online courses!

9 COMMENTS

  1. This is exactly what I was looking for. I’m using Soft Delete to inactivate users , but I have some summaries that need both active and inactive (Softdeleted) users. Very Simple and Useful solution. Thanks.

LEAVE A REPLY

Please enter your comment!
Please enter your name here