PHP
Implement Soft Deletes and Restore Models with Eloquent
Learn how to use Laravel Eloquent's soft deletes feature to gracefully "delete" records by marking them, allowing for easy restoration and data recovery.
// In App\Models\Post.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
// ... model definition ...
}
// Database Migration (add to 'posts' table)
Schema::table('posts', function (Blueprint $table) {
$table->softDeletes(); // Adds 'deleted_at' timestamp column
});
// 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
$post = App\Models\Post::withTrashed()->find(1);
$post->restore(); // Sets 'deleted_at' to null
// Force delete a post (permanently remove from DB)
$post = App\Models\Post::find(2); // If already soft-deleted, use withTrashed()
$post->forceDelete();
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 column is set on the model, indicating it's no longer "active." This is invaluable for auditing, data recovery, and avoiding accidental data loss. Eloquent automatically excludes soft-deleted records from query results unless explicitly requested using `withTrashed()` or `onlyTrashed()`. Models can then be restored using the `restore()` method or permanently removed using `forceDelete()`.