PHP
Managing Soft Deletes, Restoration, and Force Deletion in Eloquent
Learn to implement soft deletes in Laravel Eloquent, allowing records to be 'deleted' without removing them from the database, and how to restore or permanently delete them.
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
// App/Models/Task.php
class Task extends Model
{
use SoftDeletes;
protected $fillable = ['name', 'description'];
}
// Usage:
$task = Task::create(['name' => 'Complete Report', 'description' => 'Write Q4 report']);
$task->delete(); // Soft deletes the task, setting 'deleted_at' timestamp
// Retrieve only soft-deleted tasks
$deletedTasks = Task::onlyTrashed()->get();
// Retrieve all tasks, including soft-deleted ones
$allTasksIncludingDeleted = Task::withTrashed()->get();
// Restore a soft-deleted task
if ($deletedTask = Task::onlyTrashed()->first()) {
$deletedTask->restore();
echo "Task restored: " . $deletedTask->name . "
";
}
// Permanently delete a soft-deleted task
if ($deletedTask = Task::onlyTrashed()->first()) {
$deletedTask->forceDelete();
echo "Task permanently deleted.
";
}
How it works: Soft deletes in Eloquent provide a way to 'delete' records without actually removing them from your database. By using the `SoftDeletes` trait on a model, a `deleted_at` timestamp column is added to your table. When `delete()` is called, this timestamp is set instead of the row being physically removed. Eloquent then automatically excludes these 'deleted' records from regular queries. You can retrieve soft-deleted items with `onlyTrashed()` or `withTrashed()`, and use `restore()` to bring them back or `forceDelete()` to permanently remove them.