PHP

Implementing Soft Deletes for Non-Destructive Data Removal in Laravel Eloquent

Add soft delete functionality to your Laravel models, allowing records to be 'trashed' rather than permanently deleted, enabling easy restoration.

// In App\Models\Post.php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;
    // ... other model properties and methods
}

// In database migration (e.g., 2023_01_01_create_posts_table.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('content');
            $table->timestamps();
            $table->softDeletes(); // Adds 'deleted_at' timestamp column
        });
    }
    // ...
};

// Usage Example
$post = App\Models\Post::find(1);
$post->delete(); // Sets 'deleted_at' timestamp, doesn't remove from DB

$trashedPosts = App\Models\Post::onlyTrashed()->get(); // Retrieve only soft-deleted records
$allPostsIncludingTrashed = App\Models\Post::withTrashed()->get(); // Retrieve all, including soft-deleted

$post->restore(); // Clears 'deleted_at' timestamp, restoring the record
$post->forceDelete(); // Permanently removes the record from the database
How it works: Soft deletes in Eloquent provide a way to 'archive' records instead of permanently deleting them from your database. By using the `SoftDeletes` trait and adding a `deleted_at` timestamp column to your table, calling the `delete()` method on a model will set this timestamp rather than physically removing the row. This allows you to easily retrieve, restore, or even force-delete these 'trashed' records later, adding a layer of data recovery and auditing to your application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs