PHP

Implement and Query Eloquent Soft Deletes

Learn to implement soft deletes in Laravel Eloquent models, allowing records to be 'deleted' without actual database removal, and how to query, restore, or force delete them.

// In your User model (App\Models\User.php)
// use Illuminate\Database\Eloquent\SoftDeletes;
//
// class User extends Model
// {
//     use SoftDeletes;
//     // ...
// }

use App\Models\User;

// Soft delete a user
$user = User::find(1);
$user->delete(); // Sets 'deleted_at' timestamp

// Retrieve all users, including soft deleted
$allUsers = User::withTrashed()->get();

// Retrieve only soft deleted users
$trashedUsers = User::onlyTrashed()->get();

// Restore a soft deleted user
$trashedUser = User::onlyTrashed()->find(1);
if ($trashedUser) {
    $trashedUser->restore(); // Clears 'deleted_at' timestamp
}

// Permanently delete a user (even if soft deleted)
$userToForceDelete = User::withTrashed()->find(2);
if ($userToForceDelete) {
    $userToForceDelete->forceDelete(); // Removes record from database
}
How it works: This snippet illustrates how to implement and interact with Eloquent's soft delete functionality. By using the `SoftDeletes` trait, models are not physically removed from the database upon deletion; instead, their `deleted_at` timestamp is set. The snippet shows how to retrieve all records (including soft deleted), only soft deleted records, restore a soft deleted record, and permanently delete a record using `forceDelete()`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs