Member-only story
Soft Delete in Laravel
Soft deleting allows you to mark models as “deleted” without actually removing them from the database. It works by adding a deleted_at
column, which stores the timestamp of when an entry is deleted.
The major advantage of soft deletes is that you don’t lose data permanently — deleted entries can always be restored later.
Laravel also provides a mechanism to clean up older soft deleted records, which I’ll explain later.
How to Set Up Soft Deletes
Configuring soft deletes in Laravel is straightforward. There are two key steps:
1. Modify your migration
First, you need to add a column for soft deletes in your migration file. After running the migration, a deleted_at
column will be added to your table (e.g., posts
).
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->softDeletes();
});
}
To remove the column during rollback, use the dropSoftDeletes()
method in the down()
function.
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
2. Update your model
Next, in your model, import the SoftDeletes
trait to enable soft delete functionality.