PHP
Implement Soft Deletes for Logical Deletion in Eloquent
Use Laravel Eloquent's soft deletes to logically remove records without permanently deleting them, allowing for easy restoration and historical data retention.
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
// ... model properties and relationships ...
}
// Migration for adding deleted_at column
// Schema::table('posts', function (Blueprint $table) {
// $table->softDeletes();
// });
// Usage:
$post = Post::find(1);
$post->delete(); // Sets `deleted_at` timestamp, doesn't permanently remove
// Retrieve only non-deleted posts (default behavior)
$activePosts = Post::all();
// Retrieve all posts, including soft deleted ones
$allPosts = Post::withTrashed()->get();
// Retrieve only soft deleted posts
$deletedPosts = Post::onlyTrashed()->get();
// Restore a soft deleted post
$post->restore();
// Permanently delete a post
$post->forceDelete();
How it works: Soft deletes provide a way to 'delete' records by setting a `deleted_at` timestamp instead of physically removing them from the database. By using the `SoftDeletes` trait on your Eloquent model, queries will automatically exclude soft-deleted records. You can then use methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` to manage these logically deleted items, offering an undo mechanism and data retention.