Laravel soft deletes for data retention

Carlos Mendez Jan 2026
3 tabs
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
            $table->softDeletes(); // Adds deleted_at column
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
3 files · php Explain with highlit

Soft deletes mark records as deleted without removing them from the database, enabling recovery and audit trails. I add SoftDeletes trait to models and a deleted_at timestamp column. Calling delete() sets deleted_at instead of removing rows. Soft-deleted models are automatically excluded from queries. The withTrashed() method includes deleted records, while onlyTrashed() retrieves only deleted ones. The restore() method undeletes records. Force deletion with forceDelete() permanently removes rows. Soft deletes work with relationships—cascading soft deletes keep data consistent. This pattern is essential for regulatory compliance, user data recovery, and maintaining referential integrity.