PHP
Implement Soft Deletion for Eloquent Models in Laravel
Learn to implement soft deletes in Laravel Eloquent, allowing you to gracefully 'delete' records by marking them without truly removing data from your database.
// In App\Models\Post.php
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at']; // Laravel 8+ handles this automatically with SoftDeletes trait
}
// Usage
$post = App\Models\Post::find(1);
$post->delete(); // Soft deletes the post
$allPosts = App\Models\Post::all(); // Does not include soft-deleted posts
$trashedPosts = App\Models\Post::onlyTrashed()->get(); // Includes only soft-deleted posts
$withTrashedPosts = App\Models\Post::withTrashed()->get(); // Includes all posts (deleted and non-deleted)
$post->restore(); // Restores a soft-deleted post
$post->forceDelete(); // Permanently deletes a soft-deleted post
How it works: Soft deletes in Laravel Eloquent provide a way to 'delete' records without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. This allows for data recovery and audit trails. The `withTrashed()`, `onlyTrashed()`, and `restore()` methods provide convenient ways to interact with soft-deleted records, while `forceDelete()` performs a permanent removal.