PHP
Implementing Logical Deletion with Eloquent Soft Deletes
Understand how to use Eloquent's soft deletes to logically remove records from your database without actually deleting them, allowing for recovery and audit trails.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Comment extends Model
{
use SoftDeletes;
// By default, soft deleted models are excluded from query results.
// Example usage in a controller:
// $comment = Comment::find(1);
// $comment->delete(); // Sets 'deleted_at' timestamp
// To retrieve all comments, including soft deleted ones:
// $allComments = Comment::withTrashed()->get();
// To retrieve only soft deleted comments:
// $deletedComments = Comment::onlyTrashed()->get();
// To restore a soft deleted comment:
// $comment->restore(); // Sets 'deleted_at' back to null
// To permanently delete a comment:
// $comment->forceDelete();
}
How it works: Soft deletes provide a way to 'logically' delete records without actually removing them from your database. Instead of a full deletion, a `deleted_at` timestamp column is set on the record. Eloquent then automatically excludes these 'deleted' records from all future query results. This is useful for maintaining audit trails, allowing users to restore deleted items, or preventing accidental data loss. To enable soft deletes, you simply add the `Illuminate\Database\Eloquent\SoftDeletes` trait to your model.