PHP

Implement Non-Destructive Data Deletion with Eloquent Soft Deletes

Learn how to use Laravel Eloquent's soft delete feature to mark database records as deleted without permanently removing them, enabling easy restoration and audit trails.

<?php

// 1. Add 'deleted_at' column to your table (e.g., using a migration)
// Schema::table('posts', function (Blueprint $table) {
//     $table->softDeletes();
// });

// 2. In your Post model (app/Models/Post.php)
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at']; // Optional: For older Laravel versions or explicit casting
}

// Usage examples:

// Soft deleting a record:
$post = Post::find(1);
$post->delete(); // Sets 'deleted_at' timestamp, doesn't remove from DB

// Retrieving all non-soft-deleted records (default):
$activePosts = Post::all();

// Retrieving all records including soft-deleted:
$allPosts = Post::withTrashed()->get();

// Retrieving ONLY soft-deleted records:
$trashedPosts = Post::onlyTrashed()->get();

// Restoring a soft-deleted record:
$post = Post::withTrashed()->find(1);
$post->restore(); // Sets 'deleted_at' to null

// Force deleting a record (permanently removes from DB):
$post = Post::find(2);
$post->forceDelete();

// Check if a model instance is soft deleted
$post = Post::withTrashed()->find(1);
if ($post->trashed()) {
    echo "This post is soft-deleted.
";
}
How it works: Eloquent's soft deletes provide a convenient way to 'delete' records without actually removing them from your database. Instead of a permanent deletion, a `deleted_at` timestamp column on the record is set. This allows you to easily retrieve, restore, or even permanently delete these records later. It's an excellent feature for applications requiring data recovery, auditing, or a 'trash can' functionality, ensuring data integrity and preventing accidental data loss.

Need help integrating this into your project?

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

Hire DigitalCodeLabs