PHP
Manage Data Lifecycle with Eloquent Soft Deletes
Gracefully remove records from queries without permanently deleting them using Eloquent's soft deletes, allowing for easy restoration and auditing.
<?php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
// In App\Models\Post (Example model)
class Post extends Model
{
use SoftDeletes; // Add this trait
}
// Delete a record (soft deletes it)
$post = App\Models\Post::find(1);
if ($post) {
$post->delete();
echo "Post ID 1 soft deleted.
";
}
// Retrieve all records, including soft deleted ones
$allPosts = App\Models\Post::withTrashed()->get();
echo "Total posts (including deleted): " . $allPosts->count() . "
";
// Retrieve only soft deleted records
$deletedPosts = App\Models\Post::onlyTrashed()->get();
echo "Only deleted posts: " . $deletedPosts->count() . "
";
// Restore a soft deleted record (assuming post ID 1 was deleted)
$restoredPost = App\Models\Post::withTrashed()->find(1);
if ($restoredPost && $restoredPost->trashed()) {
$restoredPost->restore();
echo "Post ID 1 restored: " . $restoredPost->title . "
";
}
// Permanently delete a record (assuming ID 2 is soft deleted)
$postToForceDelete = App\Models\Post::onlyTrashed()->find(2);
if ($postToForceDelete) {
$postToForceDelete->forceDelete();
echo "Post ID 2 permanently deleted: " . $postToForceDelete->title . "
";
}
How it works: Soft deletes in Eloquent allow you to "delete" records by setting a `deleted_at` timestamp rather than actually removing them from the database. This is achieved by adding the `SoftDeletes` trait to your model and a `deleted_at` column to your table. You can then use methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` to manage the lifecycle of these records.