PHP
Implement Soft Deletes in Laravel Eloquent Models
Discover how to implement soft deletes in your Laravel Eloquent models, allowing you to gracefully archive records instead of permanently deleting them, preserving data.
<?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, Eloquent will look for a 'deleted_at' column.
// You can customize the column name if needed:
// const DELETED_AT = 'archived_at';
}
// To enable soft deletes, you need a 'deleted_at' column in your migration:
/*
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->decimal('price', 8, 2);
$table->timestamps();
$table->softDeletes(); // Adds 'deleted_at' TIMESTAMP NULLABLE
});
*/
// Example Usage:
// $product = App\Models\Product::find(1);
// $product->delete(); // Sets 'deleted_at' timestamp
// $allProducts = App\Models\Product::all(); // Only active (not soft-deleted) products
// $trashedProducts = App\Models\Product::onlyTrashed()->get(); // Only soft-deleted products
// $allIncludingTrashed = App\Models\Product::withTrashed()->get(); // All products
// $product->restore(); // Un-deletes a soft-deleted product
// $product->forceDelete(); // Permanently deletes a soft-deleted product
How it works: Soft Deletes allow you to 'delete' models without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. This is useful for auditing, data recovery, or simply keeping historical data. To enable, add the `SoftDeletes` trait to your model and a `deleted_at` column to your table migration. Eloquent will then automatically exclude soft-deleted records from standard queries.