PHP

Implement Non-Destructive Deletion with Laravel Eloquent Soft Deletes

Preserve valuable data by implementing soft deletes in Laravel Eloquent, allowing you to 'delete' records without permanently removing them from the database.

<?php

namespace App\Models;

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

class Post extends Model
{
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
}

// In your application logic:

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

// Retrieving posts (soft-deleted posts are automatically excluded):
$allPosts = Post::all();

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

// Retrieving ALL posts (including soft-deleted ones):
$allPostsIncludingTrashed = Post::withTrashed()->get();

// Restoring a soft-deleted post:
$trashedPost = Post::onlyTrashed()->find(1);
if ($trashedPost) {
    $trashedPost->restore(); // Sets 'deleted_at' to null
}

// Permanently deleting a post (bypassing soft deletes):
$postToForceDelete = Post::find(2);
$postToForceDelete->forceDelete(); // Permanently removes from DB
How it works: Soft deleting allows you to 'delete' models without actually removing them from your database. When a model is soft deleted, a `deleted_at` timestamp is set on the record. Eloquent queries will then automatically exclude soft-deleted records. This snippet demonstrates how to enable soft deletes using the `SoftDeletes` trait, how to delete and restore records, and how to query both regular and soft-deleted items. It also shows `forceDelete()` for permanent removal.

Need help integrating this into your project?

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

Hire DigitalCodeLabs