← Back to all snippets
PHP

Implement Soft Deletes for Non-Destructive Data Removal

Enable soft deletion in Laravel Eloquent models to gracefully 'delete' records without removing them permanently from the database, allowing for restoration.

<?php

namespace App\Models;

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

class Product extends Model
{
    use SoftDeletes;

    protected $fillable = ['name', 'price'];

    // By default, only non-deleted products are retrieved.
    // Product::all();

    // Retrieve all products, including soft-deleted ones.
    // Product::withTrashed()->get();

    // Retrieve only soft-deleted products.
    // Product::onlyTrashed()->get();

    // Soft delete a product
    // $product = Product::find(1);
    // $product->delete(); // Sets 'deleted_at' timestamp

    // Restore a soft-deleted product
    // $trashedProduct = Product::withTrashed()->find(1);
    // $trashedProduct->restore();

    // Permanently delete a product (bypassing soft deletes)
    // $trashedProduct = Product::onlyTrashed()->find(1);
    // $trashedProduct->forceDelete();
}
How it works: The `SoftDeletes` trait in Laravel Eloquent allows models to be 'soft deleted' instead of permanently removed from the database. When a model is soft deleted, its `deleted_at` timestamp is set, but the record remains in the table. This enables features like a 'trash can' or recovery of deleted items. The snippet illustrates how to apply the trait, and briefly mentions methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` for interacting with soft-deleted records.

Need help integrating this into your project?

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

Hire DigitalCodeLabs