Skip to main content
Tutorial Free Preview

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

July 06, 2015
1 min read
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();
}

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.