PHP
Implement Soft Deletion for Records with Laravel Eloquent
Utilize Laravel Eloquent's soft deletes feature to logically remove records by setting a 'deleted_at' timestamp instead of actual database deletion.
// In App/Models/Post.php
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at']; // Optional, but good practice
}
// Usage:
$post = App\Models\Post::find(1);
$post->delete(); // Soft deletes the post
// Retrieve all posts, including soft-deleted ones
$allPosts = App\Models\Post::withTrashed()->get();
// Retrieve only soft-deleted posts
$deletedPosts = App\Models\Post::onlyTrashed()->get();
// Restore a soft-deleted post
$post->restore();
// Permanently delete a soft-deleted post
$post->forceDelete();
How it works: Soft Deletes enable 'logical' deletion of models by setting a `deleted_at` timestamp rather than physically removing the record from the database. This allows for data recovery and audit trails. By using the `SoftDeletes` trait, you gain access to methods like `delete()`, `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()`, providing comprehensive control over the lifecycle of your models.