PHP
Managing Model Lifecycles with Soft Deletes
Implement soft deletes in Laravel Eloquent to gracefully "delete" records by marking them, allowing restoration or permanent deletion later, enhancing data integrity.
use Illuminate\Database\Eloquent\SoftDeletes;
// app/Models/Product.php
class Product extends Model
{
use SoftDeletes;
// ...
}
// Delete a product (soft delete)
$product = Product::find(1);
$product->delete(); // 'deleted_at' column is set
// Retrieve soft deleted products
$deletedProducts = Product::onlyTrashed()->get();
// Retrieve all products including soft deleted ones
$allProducts = Product::withTrashed()->get();
// Restore a soft deleted product
$product->restore(); // 'deleted_at' is set to null
// Permanently delete a product
$product->forceDelete();
How it works: Soft Deletes provide a way to "delete" records without actually removing them from your database. Instead, a `deleted_at` timestamp is set. This snippet demonstrates how to enable soft deletes on an Eloquent model using the `SoftDeletes` trait, and then how to perform soft deletions, retrieve only soft-deleted items (`onlyTrashed()`), retrieve all items including soft-deleted ones (`withTrashed()`), restore soft-deleted items, and finally, permanently delete records using `forceDelete()`.