Soft Deletes

What are Soft Deletes?

Soft Deletes in Laravel allow you to mark records as deleted without permanently removing them from the database. This feature is useful for retaining data while hiding it from active queries.


Origin

Soft Deletes were introduced to help developers manage data retention without requiring manual archive tables or processes. It leverages an additional deleted_at column in the database to track deletion timestamps.


Why are they important?

  1. Data Recovery: Soft Deletes allow deleted records to be restored effortlessly.
  2. Non-Destructive Deletion: Prevents permanent loss of data, which is crucial for compliance or auditing.
  3. Query Flexibility: Developers can include or exclude soft-deleted records based on the query requirements.

Best Practices

  1. Enable Soft Deletes Only Where Needed: Use soft deletes on models where data recovery is essential.
  2. Use Scopes for Filtering: Utilize Laravel's built-in onlyTrashed and withTrashed scopes to manage soft-deleted records.
  3. Purge Old Data: Regularly purge soft-deleted records that are no longer needed using scheduled tasks.

Example in Action

To enable soft deletes on a model, add the SoftDeletes trait:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

When deleting a record, Laravel sets the deleted_at column instead of removing the record:

$post = Post::find(1);
$post->delete();

To restore a soft-deleted record:

Post::withTrashed()->find(1)->restore();

To permanently delete a soft-deleted record:

Post::onlyTrashed()->find(1)->forceDelete();

This approach ensures that data is retained safely while allowing flexibility for retrieval or permanent removal.