PHP
Implementing Soft Deletes and Restoring Models in Eloquent
Discover how to use Laravel's soft deleting feature to "archive" records instead of permanently deleting them, with options to restore.
// app/Models/Product.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $fillable = ['name', 'price'];
// Optionally define the column name for deleted timestamp
// const DELETED_AT = 'deleted_on';
}
// Example Usage: Deleting
$product = App\Models\Product::find(1);
$product->delete(); // Sets 'deleted_at' timestamp, doesn't remove from DB
// Example Usage: Retrieving soft-deleted models
$allProducts = App\Models\Product::withTrashed()->get();
$deletedProducts = App\Models\Product::onlyTrashed()->get();
// Example Usage: Restoring
$deletedProduct = App\Models\Product::onlyTrashed()->find(1);
if ($deletedProduct) {
$deletedProduct->restore(); // Sets 'deleted_at' back to null
}
// Example Usage: Force Deleting
$productToForceDelete = App\Models\Product::withTrashed()->find(2);
if ($productToForceDelete) {
$productToForceDelete->forceDelete(); // Permanently removes from DB
}
How it works: Soft Deleting allows you to "delete" models without actually removing them from your database. Instead, a `deleted_at` timestamp is set on the record. Eloquent queries will then automatically exclude these soft-deleted records. The `withTrashed()` method allows you to retrieve all records (including soft-deleted ones), while `onlyTrashed()` retrieves only the soft-deleted ones. Models can be restored using the `restore()` method or permanently deleted with `forceDelete()`.