Soft Deleting in Laravel

What is Soft Deleting in Laravel?

Soft deletion in Laravel enables you to designate entries as removed without permanently removing them from the database. This functionality is great for storing data while keeping it out of active searches, ensuring flexibility and data recoverability.


Origin

Soft deletion was added in Laravel to simplify data retention and recovery by eliminating the requirement for separate archive tables or manual methods. It works by creating a deleted_at column in the database that stores the timestamp of a soft delete.


Why Is Soft Deleting Used?

  1. Data Recovery: Allows you to easily restore records that were unintentionally deleted or subsequently needed.
  2. Non-Destructive Deletion: Prevents permanent data loss while meeting compliance and auditing requirements.
  3. Query Flexibility: It lets developers include, omit, or retrieve only soft-deleted records based on their queries.

Best Practices.

  1. Use Soft Deletes Only When Necessary: Use soft deleting on models where data recovery is critical.
  2. Leverage Laravel's Built-in Scopes: Such as onlyTrashed and withTrashed, to efficiently handle soft-deleted data.
  3. Clean Up Frequently: Schedule regular actions to remove old, unwanted, soft-deleted entries. This will optimize the database.

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();

Read more