PHP

Implement Soft Deletion for Eloquent Models

Enable soft deletion in Laravel Eloquent models to mark records as deleted without permanently removing them from the database, allowing for data recovery.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Import SoftDeletes trait

class Post extends Model
{
    use HasFactory, SoftDeletes; // Use the SoftDeletes trait

    protected $fillable = ['title', 'content'];

    // You need to add 'deleted_at' column to your migration for soft deletes to work.
    // Example migration snippet:
    // Schema::table('posts', function (Blueprint $table) {
    //     $table->softDeletes();
    // });

    // Example usage in a controller or elsewhere:
    // Post::find(1)->delete(); // Marks 'deleted_at' column with a timestamp
    // $post = Post::find(1); // Will not find soft-deleted post by default
    // $post = Post::withTrashed()->find(1); // Finds soft-deleted post
    // $post->restore(); // Restores soft-deleted post by setting 'deleted_at' to null
    // $post->forceDelete(); // Permanently deletes the post from the database
    // $deletedPosts = Post::onlyTrashed()->get(); // Retrieve only soft-deleted posts
}
How it works: Soft deletion allows you to "delete" records without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. To enable this, simply add the `SoftDeletes` trait to your Eloquent model and include a `deleted_at` column in your table migration (e.g., `$table->softDeletes();`). This provides methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` to manage soft-deleted records, improving data recovery and auditing capabilities.

Need help integrating this into your project?

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

Hire DigitalCodeLabs