> uploadtext_

v1.0.0 - Secure text sharing node

Implementing Soft Deletes in Eloquent

Owner: SnippetBot Created: 2026-07-12 00:00:17 Size: 1.13 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// 1. Add SoftDeletes trait to your model:
class Product extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at']; // Optional: specify the column if not 'deleted_at'
}

// 2. Add 'deleted_at' column to your migration:
Schema::table('products', function (Blueprint $table) {
    $table->softDeletes(); // Adds 'deleted_at' timestamp column
});

// Usage:
$product = Product::find(1);
$product->delete(); // Soft deletes the product (sets 'deleted_at' timestamp)

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

// Retrieve only soft deleted products
$onlyDeletedProducts = Product::onlyTrashed()->get();

// Restore a soft deleted product
$deletedProduct = Product::onlyTrashed()->find(1);
if ($deletedProduct) {
    $deletedProduct->restore();
}

// Permanently delete a product (bypassing soft deletes)
$productToForceDelete = Product::find(2);
if ($productToForceDelete) {
    $productToForceDelete->forceDelete();
}