PHP
Implementing and Querying Soft Deleted Models
Learn to enable soft deletes in Laravel Eloquent models, allowing records to be 'deleted' without being permanently removed from the database, and how to query and restore them.
<?php
// app/Models/Task.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Task extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at']; // Make sure 'deleted_at' is cast to a Carbon instance
}
// Migrations (create_tasks_table.php)
// ...
// $table->softDeletes();
// ...
// Usage Example
// Soft delete a task
$task = Task::find(1);
$task->delete(); // 'deleted_at' column is set
// Retrieve tasks without soft-deleted ones (default behavior)
$activeTasks = Task::all();
// Retrieve all tasks, including soft-deleted ones
$allTasks = Task::withTrashed()->get();
// Retrieve only soft-deleted tasks
$deletedTasks = Task::onlyTrashed()->get();
// Restore a soft-deleted task
$trashedTask = Task::onlyTrashed()->find(1);
if ($trashedTask) {
$trashedTask->restore(); // 'deleted_at' column is set to null
}
// Permanently delete a task
$taskToDelete = Task::find(2);
$taskToDelete->forceDelete(); // Permanently removes the record from the database
How it works: Soft deletes in Laravel allow you to "delete" models without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. To enable soft deletes, use the `Illuminate\Database\Eloquent\SoftDeletes` trait in your model and add the `softDeletes()` column to your table migration. By default, Eloquent queries will exclude soft-deleted models. You can include them using `withTrashed()`, retrieve only soft-deleted models with `onlyTrashed()`, restore them with `restore()`, or permanently delete them with `forceDelete()`.