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(); }
Is this soft delete a built in feature in Laravel?
Amos, yes it is: http://laravel.com/docs/5.1/eloquent#soft-deleting
Thanks! this solved my issue!
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.
Thank you so much! Save my day!
Thank you. Solved my issue too. The relating model should use SoftDeletingTrait though.
Thanks a lot !
Solved mine too …
A quick google and this post was my solution. Thanks so much.
how to restore child data if parent restored..
Thank you so much ! this solved my problem!