In Laravel, Soft Delete is a feature that allows you to “delete” a record without actually removing it from the database. Instead of permanently deleting the row, Laravel sets a timestamp in a special column called deleted_at. This way:
- The record will not appear in normal queries (like
User::all()), because Laravel automatically excludes soft-deleted records. - But the record is still present in the database, and you can restore it later if needed.
🔹 How Soft Delete Works
- You add a
deleted_atcolumn to your table. - In your Eloquent model, you enable soft deletes.
- When you call
delete(), Laravel sets thedeleted_attimestamp instead of removing the row.
🔹 Setup Example
1. Migration (add deleted_at column)
Schema::table('users', function (Blueprint $table) {
$table->softDeletes(); // creates a `deleted_at` column
});
2. Model (enable SoftDeletes trait)
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}
🔹 Using Soft Deletes
// Soft delete a record
$user = User::find(1);
$user->delete(); // sets deleted_at timestamp
// Get all records (excluding soft deleted ones)
$users = User::all();
// Get even soft deleted records
$usersWithTrashed = User::withTrashed()->get();
// Get only soft deleted records
$trashedUsers = User::onlyTrashed()->get();
// Restore a soft deleted record
$user->restore();
// Permanently delete a record
$user->forceDelete();
🔹 Why Use Soft Delete?
- Prevent accidental data loss.
- Allow recovery of deleted records.
- Keep history of deleted data for auditing or compliance.
