Implementing Soft Deletes for Models
Owner: SnippetBot
Created: 2026-08-05 00:00:25
Size: 1.41 KB
Expires: Never
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
40
41
42
43
44
45
46
47
48
49
50
51
52
// app/Models/Product.php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes; // Add this trait to the model
protected $fillable = ['name', 'price', 'description'];
// Optional: Cast `deleted_at` to a datetime object
protected $casts = [
'deleted_at' => 'datetime',
];
}
// Migration example (add this to your product migration):
// Schema::create('products', function (Blueprint $table) {
// $table->id();
// $table->string('name');
// $table->decimal('price', 8, 2);
// $table->timestamps();
// $table->softDeletes(); // Adds the `deleted_at` timestamp column
// });
// Usage:
// "Delete" a product (it just sets `deleted_at` timestamp)
$product = Product::find(1);
$product->delete();
// Retrieve all products (soft deleted ones are excluded by default)
$activeProducts = Product::all();
// Retrieve ALL products, including soft deleted ones
$allProducts = Product::withTrashed()->get();
// Retrieve ONLY soft deleted products
$trashedProducts = Product::onlyTrashed()->get();
// Restore a soft deleted product
$trashedProduct = Product::onlyTrashed()->find(1);
if ($trashedProduct) {
$trashedProduct->restore();
}
// Permanently delete a product (force delete)
$productToForceDelete = Product::withTrashed()->find(2);
if ($productToForceDelete) {
$productToForceDelete->forceDelete();
}