PHP

Implementing Soft Deletes for Eloquent Models

Add soft delete functionality to your Laravel Eloquent models, allowing records to be 'trashed' instead of permanently deleted, with restoration options.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes;

    // ... model definition ...
}

// In your migration for the 'posts' table:
// $table->softDeletes();

// --- Usage Examples ---

// Deleting a post (soft delete)
$post = Post::find(1);
if ($post) {
    $post->delete(); // 'deleted_at' timestamp is set
}

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

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

// Restoring a soft deleted post
$trashedPost = Post::withTrashed()->find(1);
if ($trashedPost && $trashedPost->trashed()) {
    $trashedPost->restore(); // 'deleted_at' is set to null
}

// Force deleting a post (permanent deletion)
$postToForceDelete = Post::onlyTrashed()->find(2);
if ($postToForceDelete) {
    $postToForceDelete->forceDelete();
}
How it works: Soft deleting allows you to 'archive' records without permanently removing them from your database. By using the `SoftDeletes` trait on an Eloquent model and adding a `deleted_at` timestamp column to your table, records will no longer be retrieved by standard queries after calling `delete()`. Laravel automatically filters them out. You can then use methods like `withTrashed()`, `onlyTrashed()`, and `restore()` to interact with these 'trashed' records, providing a robust way to manage data lifecycle.

Need help integrating this into your project?

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

Hire DigitalCodeLabs