PHP

Implementing and Managing Soft Deletes in Eloquent

Use Laravel Eloquent's soft deletes to gracefully "delete" records without permanent removal, enabling easy restoration and full deletion when truly necessary.

// In app/Models/Product.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Don't forget this trait

class Product extends Model
{
    use SoftDeletes;

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

// In a controller or route
use App\Models\Product;

// Create a product
$product = Product::create(['name' => 'Laptop', 'price' => 1200.00]);
echo "Product created: " . $product->name . "
";

// Soft delete the product
$product->delete();
echo "Product soft deleted.
";

// Attempt to find it (will not find soft-deleted by default)
$foundProduct = Product::find($product->id);
echo "Found product (after soft delete): " . ($foundProduct ? $foundProduct->name : 'None') . "
";

// Find soft-deleted products
$trashedProduct = Product::withTrashed()->find($product->id);
echo "Found trashed product: " . ($trashedProduct ? $trashedProduct->name : 'None') . "
";

// Only trashed products
$onlyTrashedProducts = Product::onlyTrashed()->get();
echo "Only trashed products count: " . $onlyTrashedProducts->count() . "
";

// Restore the product
if ($trashedProduct) {
    $trashedProduct->restore();
    echo "Product restored.
";
}

// Force delete (permanently remove)
$productToDeletePermanently = Product::create(['name' => 'Mouse', 'price' => 25.00]);
$productToDeletePermanently->forceDelete();
echo "Product force deleted permanently.
";
How it works: Soft Deletes in Eloquent allow you to mark records as "deleted" by setting a `deleted_at` timestamp rather than actually removing them from the database. This is invaluable for auditing, accidental deletion recovery, or data retention policies. By using the `SoftDeletes` trait, your model gains methods like `delete()`, `restore()`, `withTrashed()`, `onlyTrashed()`, and `forceDelete()`, providing comprehensive control over the lifecycle of "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