PHP
Implement Non-Destructive Deletion with Eloquent Soft Deletes
Master Laravel Eloquent's soft deletes to mark database records as deleted without permanently removing them, enabling data recovery and maintaining historical integrity in your applications.
// 1. Add 'deleted_at' column to your table via migration (example):
// Schema::table('posts', function (Blueprint $table) {
// $table->softDeletes();
// });
// 2. In your App\Models\Post model:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Add this line
class Post extends Model
{
use SoftDeletes; // Use the trait
// For Laravel 8+, the SoftDeletes trait automatically handles the 'deleted_at' column.
// In older versions, you might need: protected $dates = ['deleted_at'];
}
// Usage:
$post = App\Models\Post::find(1);
if ($post) {
$post->delete(); // This sets the 'deleted_at' timestamp, not remove the row.
echo "Post ID 1 soft-deleted.
";
}
// Retrieve active posts (default behavior - soft-deleted items are excluded)
$activePosts = App\Models\Post::all();
echo "Active posts count: " . $activePosts->count() . "
";
// Retrieve all posts, including soft-deleted ones
$allPosts = App\Models\Post::withTrashed()->get();
echo "All posts (including trashed) count: " . $allPosts->count() . "
";
// Retrieve only soft-deleted posts
$trashedPosts = App\Models\Post::onlyTrashed()->get();
echo "Trashed posts count: " . $trashedPosts->count() . "
";
// Restore a soft-deleted post
$trashedPost = App\Models\Post::withTrashed()->find(1);
if ($trashedPost && $trashedPost->trashed()) {
$trashedPost->restore();
echo "Post ID 1 restored.
";
}
// Permanently delete a post (force delete) - BE CAREFUL!
$postToForceDelete = App\Models\Post::find(2); // Assuming post ID 2 exists
if ($postToForceDelete) {
$postToForceDelete->forceDelete();
echo "Post ID 2 permanently deleted.
";
}
How it works: Soft deletes in Laravel Eloquent provide a powerful mechanism to 'delete' records without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. When retrieving models, Eloquent automatically excludes soft-deleted records. This feature is invaluable for maintaining data integrity, auditing purposes, or allowing users to restore mistakenly deleted items. The `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` methods offer comprehensive control over soft-deleted records, providing flexibility in data management.