PHP
Implementing Soft Deletes for Logical Data Deletion in Laravel Eloquent
Use Laravel's soft deletes feature to logically delete records instead of physically removing them, preserving data integrity and allowing for easy restoration.
// In Post model:
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
// Usage:
$post = Post::find(1);
$post->delete(); // Soft deletes the record
Post::withTrashed()->get(); // Retrieve all, including soft deleted
Post::onlyTrashed()->get(); // Retrieve only soft deleted
$post->restore(); // Restore a soft deleted record
How it works: Soft deletes allow you to 'delete' records by setting a `deleted_at` timestamp rather than permanent removal from the database. This preserves data for auditing or potential restoration. The `SoftDeletes` trait adds methods like `delete()`, `withTrashed()`, `onlyTrashed()`, and `restore()` to your model, providing full control over logically deleted records.