How to Implement Soft Deletes and Restore Data
Data deletion is a sensitive process in any web application. Accidentally removing records from your database can lead to permanent data loss, broken relationships, and user dissatisfaction. Fortunately, Laravel offers a built-in solution to handle deletions safely — Soft Deletes.
Soft deletes allow you to “delete” records without actually removing them from the database. Instead, Laravel marks the record as deleted, giving you the flexibility to restore it later. In this blog, we’ll explore how to implement soft deletes and restore data in Laravel, along with best practices and common use cases.
What Are Soft Deletes in Laravel?
In most systems, when you delete a record, it’s permanently removed from the database. This is known as a hard delete. However, there are many situations where you may need to restore deleted data later — for example, restoring a deleted user, recovering an order, or auditing changes.
Soft deletes provide a safer alternative by simply marking the record as deleted using a timestamp in a special column, typically named deleted_at. This ensures that the record remains in the database but is excluded from standard queries unless explicitly included.
Why Use Soft Deletes?
Here are a few reasons why soft deletes are a best practice in Laravel applications:
1. Data Recovery
If a record is deleted accidentally, it can easily be restored without database intervention.
2. Audit Trails and Compliance
You can track what was deleted and when — crucial for audit logs or legal compliance in applications that handle sensitive data.
3. Relationship Integrity
Soft deletes prevent cascading data loss in related models, preserving relational integrity.
4. Improved User Experience
Many platforms allow users to “undo” or “restore” deleted content. Soft deletes make this simple to implement.
Setting Up Soft Deletes in Laravel
Implementing soft deletes in Laravel is straightforward. Let’s go through the steps needed to enable and use them effectively.
Step 1: Add the deleted_at Column
First, you need to add a deleted_at column to the table where you want soft deletes. Update your migration file like this:
Then run the migration command:
This adds a nullable deleted_at column to your table, which Laravel will use to mark records as deleted.
Step 2: Enable Soft Deletes in the Model
Next, open the corresponding Eloquent model (for example, User.php) and include the SoftDeletes trait:
This tells Laravel to handle delete and restore operations through the soft delete mechanism instead of permanently removing data.
Step 3: Perform Soft Delete Operations
After enabling soft deletes, any call to delete() on your model will now mark the record as deleted instead of removing it.
Behind the scenes, Laravel sets the deleted_at column to the current timestamp. The record will no longer appear in normal queries.
Step 4: Restoring Soft Deleted Records
If you want to restore a record that was soft deleted, Laravel makes it simple. You can use the restore() method:
The withTrashed() method allows you to include soft deleted records in your query, and restore() resets the deleted_at column to null, effectively bringing the record back.
Step 5: Permanently Deleting Soft Deleted Records
If you want to remove a record completely from the database (also known as a force delete), use the forceDelete() method:
This action permanently deletes the record, removing it from the table entirely.
Querying Soft Deleted Records
Laravel provides multiple query builder methods to work with soft deleted data:
1. Excluding Soft Deleted Records
By default, Laravel automatically excludes soft deleted records when you run queries like User::all().
2. Including Soft Deleted Records
If you need to include soft deleted records, use withTrashed():
3. Only Soft Deleted Records
To fetch only deleted records, use onlyTrashed():
These query methods give you precise control over what type of data you want to retrieve.
Real-World Use Cases for Soft Deletes
Soft deletes are valuable in several real-world scenarios. Here are a few examples:
1. User Management Systems
When an admin deletes a user, you may not want to lose their posts, comments, or orders. Soft deletes ensure user data can be restored later.
2. E-Commerce Orders
If an order is canceled but later reinstated, soft deletes make it easy to recover it.
3. CMS and Blog Platforms
When authors delete articles, you can allow them to restore their content from a “trash bin.”
4. Inventory and Data Archiving
Old or expired items can be soft deleted to keep the main dataset clean while preserving records for auditing.
Best Practices for Using Soft Deletes
1. Always Use with Caution
Soft deletes make data recovery easier but can also lead to bloated databases if old records are never cleaned up. Use scheduled tasks to clear unnecessary soft deleted data.
2. Leverage Laravel’s prune Command
Laravel provides model pruning to automatically remove stale soft deleted records. Define pruning logic in your model using the prunable() method.
3. Combine with Policies or Gates
Ensure that only authorized users can restore or permanently delete data to prevent misuse.
4. Audit and Logging
Integrate soft deletes with event listeners or logging systems to track who deleted or restored a record.
5. UI/UX Considerations
If your app allows end-users to restore deleted data, provide a clear “trash” section and confirm before performing permanent deletions.
Soft Deletes in Relationships
Laravel also supports cascading soft deletes through relationships. For example, if a user has many posts, you can soft delete both the user and their posts simultaneously using model events or the SoftDeletes trait in both models.
You can also configure restores to bring back related data when the parent record is restored, maintaining data consistency across relationships.
Common Mistakes to Avoid
-
Forgetting to use
withTrashed()when you need deleted records in queries. -
Using
forceDelete()accidentally when soft deletes should be used. -
Not handling cascading deletes properly in relationships.
-
Allowing unauthorized restore operations.
Avoiding these pitfalls ensures that your implementation remains secure and efficient.
Conclusion
Soft deletes are one of Laravel’s most practical features for maintaining data safety and recoverability. Instead of losing important information forever, you can mark records as deleted and restore them when needed.
By combining soft deletes with query methods like onlyTrashed(), using model traits, and following best practices for data management, you can build more resilient and user-friendly applications.
Whether you’re developing a CMS, e-commerce system, or business application, implementing soft deletes ensures your data remains secure, restorable, and audit-ready.