PHP
Managing Eloquent Models with Soft Deletes
Learn how to implement soft deletes in Laravel Eloquent models, allowing you to gracefully "delete" records without permanent data loss, and how to query, restore, or force delete them.
<?php
// In your User model (app/Models/User.php)
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Don't forget this!
class User extends Model
{
use HasFactory, SoftDeletes; // Add SoftDeletes trait here
protected $fillable = ['name', 'email', 'password'];
// If you need to customize the deleted_at column name
// const DELETED_AT = 'custom_deleted_timestamp';
}
// Example Usage in a controller or route
use App\Models\User;
// Delete a user (soft delete)
$user = User::find(1);
if ($user) {
$user->delete(); // Sets `deleted_at` timestamp
}
// Retrieve all users, excluding soft-deleted ones (default)
$activeUsers = User::all();
// Retrieve ALL users, including soft-deleted ones
$allUsers = User::withTrashed()->get();
// Retrieve ONLY soft-deleted users
$trashedUsers = User::onlyTrashed()->get();
// Restore a soft-deleted user
$trashedUser = User::withTrashed()->find(1);
if ($trashedUser && $trashedUser->trashed()) {
$trashedUser->restore();
}
// Permanently delete a user (force delete)
$userToForceDelete = User::withTrashed()->find(2);
if ($userToForceDelete) {
$userToForceDelete->forceDelete();
}
How it works: This snippet demonstrates how to enable and manage soft deletes for Eloquent models. By using the `SoftDeletes` trait, records are not permanently removed from the database when `delete()` is called; instead, their `deleted_at` column is timestamped. This allows for data recovery and audit trails. The code shows how to fetch active, all (including trashed), or only trashed records, as well as how to restore soft-deleted models or permanently remove them using `forceDelete()`.