Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

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

Tutorial last revisioned on August 18, 2022 with Laravel 9
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(Category::class);
    }

}
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(Category::class)->withTrashed();
}

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses