HomeLARAVELWhat is Soft Delete in Laravel?

What is Soft Delete in Laravel?

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

  1. You add a deleted_at column to your table.
  2. In your Eloquent model, you enable soft deletes.
  3. When you call delete(), Laravel sets the deleted_at timestamp 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.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *