PHP
Laravel Eloquent Soft Deletes for Non-Destructive Deletion
Implement non-destructive data deletion in Laravel using Eloquent soft deletes. Learn to retrieve, restore, and permanently delete 'trashed' models.
// In your App\Models\Post.php
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
// Migration for adding 'deleted_at' column
Schema::table('posts', function (Blueprint $table) {
$table->softDeletes();
});
// Usage
$post = App\Models\Post::find(1);
$post->delete(); // Soft deletes the post (sets 'deleted_at' timestamp)
// Retrieve all posts, excluding soft-deleted ones (default behavior)
$activePosts = App\Models\Post::all();
// Retrieve all posts, including soft-deleted ones
$allPosts = App\Models\Post::withTrashed()->get();
// Retrieve only soft-deleted posts
$trashedPosts = App\Models\Post::onlyTrashed()->get();
// Restore a soft-deleted post
App\Models\Post::withTrashed()->find(1)->restore();
// Permanently delete a soft-deleted post
App\Models\Post::withTrashed()->find(1)->forceDelete();
How it works: Soft Deletes provide a way to 'delete' records without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. By using the `SoftDeletes` trait on your model, all subsequent queries will automatically exclude soft-deleted records. You can use methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` to manage these soft-deleted entries.