PHP
Implementing Non-Destructive Deletion with Eloquent Soft Deletes
Learn to use soft deletes in Laravel Eloquent to mark records as deleted without removing them from the database, allowing for restoration and preserving data integrity.
// 1. Add 'deleted_at' column to your table (migration):
// $table->softDeletes();
// 2. In App\Models\Post.php
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
// Usage:
$post = App\Models\Post::find(1);
// Soft delete a post
$post->delete(); // Sets 'deleted_at' timestamp, does not remove from DB
// Retrieve only soft-deleted posts
$deletedPosts = App\Models\Post::onlyTrashed()->get();
// Retrieve all posts, including soft-deleted ones
$allPosts = App\Models\Post::withTrashed()->get();
// Restore a soft-deleted post
$post->restore(); // Sets 'deleted_at' to NULL
// Permanently delete a post (bypassing soft deletes)
$post->forceDelete();
How it works: Soft deletes provide a way to 'delete' records without actually removing them from your database. Instead of permanent removal, a `deleted_at` timestamp is set on the record. This is highly useful for audit trails, allowing users to 'restore' items from a trash bin, or maintaining referential integrity without complex archival systems. The `SoftDeletes` trait automatically modifies queries to exclude soft-deleted records unless explicitly requested using `onlyTrashed()` or `withTrashed()`.