Trusted answers to developer questions

How to perform soft delete in Laravel

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Overview

Soft delete hides information from end-user or flags data as deleted while it still remains visible or active in your database. To perform soft delete in Laravel, you need to have a deleted_at column that should be set to default null, as it should be of timestamp data type in the model.

Assuming we are doing this for the Post model, we add use SoftDeletes; inside the model and import the following class at the top.

use Illuminate\Database\Eloquent\SoftDeletes;

That is all you need to do, so go ahead and perform your normal delete query to check it out. To get the deleted data back, you have to add ->withTrashed() to your query.

$post = Post::where(‘id’,1)->withTrashed()->get();

You will delete the data with an ID of one, assuming you have performed a soft delete on it.


Soft delete is very valuable when it comes to tracking user records and past history. It enables you to select the model you really want to delete from and the model data you want to flag as deleted to end-users of your application.

RELATED TAGS

laravel

CONTRIBUTOR

Chinweuba Elijah Azubuike
Did you find this helpful?