PHP

Implementing and Querying Soft Deletes in Laravel Eloquent

Enable soft deleting for your Laravel Eloquent models to gracefully archive records instead of permanently deleting them, with options to restore or force delete.

<?php

// Migration to add 'deleted_at' column
/*
Schema::table('posts', function (Blueprint $table) {
    $table->softDeletes();
});
*/

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

class Post extends Model
{
    use SoftDeletes;

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

// Example Usage (e.g., in a controller or route)

// Soft delete a post
$post = App\Models\Post::find(1);
$post->delete(); // 'deleted_at' column will be timestamped

// Querying soft-deleted models

// Get all non-deleted posts (default behavior)
$activePosts = App\Models\Post::all();

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

// Get only soft-deleted posts
$trashedPosts = App\Models\Post::onlyTrashed()->get();

// Find a specific soft-deleted post
$trashedPost = App\Models\Post::withTrashed()->find(1);

// Restore a soft-deleted post
$trashedPost->restore(); // Sets 'deleted_at' to null

// Permanently delete a post (even if soft-deleted)
$post->forceDelete(); // Removes record from database
How it works: Soft Deletes allow you to 'delete' Eloquent models without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. To use it, you must add a `deleted_at` column to your model's table (usually `softDeletes()` in a migration) and add the `Illuminate\Database\Eloquent\SoftDeletes` trait to your model. Eloquent queries will then automatically exclude soft-deleted records. Methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` provide control over querying and managing these archived records, offering a robust way to implement data archival.

Need help integrating this into your project?

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

Hire DigitalCodeLabs