How to Implement Soft Deletes in Laravel

How to Implement Soft Deletes in Laravel

How to Implement Soft Deletes in Laravel

Laravel's SoftDeletes trait adds a deleted_at timestamp column and automatically excludes trashed records from queries.

Step 1 — Add the Migration Column

// In your migration
Schema::table('articles', function (Blueprint $table) {
    $table->softDeletes(); // adds deleted_at nullable timestamp
});

Step 2 — Use the Trait on the Model

// app/Models/Article.php
use Illuminate\Database\Eloquent\SoftDeletes;

class Article extends Model
{
    use SoftDeletes;
}

Step 3 — Delete, Restore, and Force Delete

$article = Article::find(1);

// Soft delete — sets deleted_at, excluded from future queries
$article->delete();

// Query trashed records
$trashed = Article::onlyTrashed()->get();

// Include trashed in results
$all = Article::withTrashed()->get();

// Restore a soft-deleted record
$article->restore();

// Permanently delete
$article->forceDelete();

Step 4 — Cascade Soft Deletes to Relations

// In the Observer, manually soft-delete children
public function deleted(Article $article): void
{
    $article->comments()->delete(); // soft-deletes if Comment uses SoftDeletes
}
All Comments