PHP
Implement Soft Deletes in Laravel Eloquent
Learn how to implement soft deletes in Laravel models, allowing records to be 'trashed' instead of permanently deleted, with convenient methods for restoring and forcing deletion.
// In App\Models\Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Don't forget to import
class Post extends Model
{
use SoftDeletes; // Use the trait
}
// Usage:
// Delete a post (soft delete)
$post = App\Models\Post::find(1);
$post->delete(); // 'deleted_at' column is set
// Retrieve only non-deleted posts (default behavior)
$activePosts = App\Models\Post::all();
// Retrieve only soft-deleted posts
$trashedPosts = App\Models\Post::onlyTrashed()->get();
// Retrieve all posts (including trashed)
$allPosts = App\Models\Post::withTrashed()->get();
// Restore a soft-deleted post
$trashedPost = App\Models\Post::onlyTrashed()->find(1);
if ($trashedPost) {
$trashedPost->restore(); // 'deleted_at' is set to null
}
// Permanently delete a post
$postToDelete = App\Models\Post::withTrashed()->find(2);
if ($postToDelete) {
$postToDelete->forceDelete(); // Permanently removes from database
}
How it works: Soft Deletes allow you to 'softly' delete models, meaning they are not actually removed from your database. Instead, a `deleted_at` timestamp is set on the record. By using the `SoftDeletes` trait, Eloquent will automatically exclude soft-deleted records from standard queries. It also provides convenient methods like `onlyTrashed()`, `withTrashed()`, `restore()`, and `forceDelete()` for managing these trashed records, offering a robust 'trash can' functionality.