PHP
Implementing Soft Deletes for Logical Record Deletion
Learn how to use Laravel's Soft Deletes feature to logically delete records instead of permanently removing them, allowing for restoration.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
// Example usage in a controller or route:
/*
// Delete a post (soft delete)
$post = Post::find(1);
$post->delete();
// Retrieve all posts, including soft deleted ones
$allPosts = Post::withTrashed()->get();
// Retrieve only soft deleted posts
$trashedPosts = Post::onlyTrashed()->get();
// Restore a soft deleted post
$trashedPost = Post::withTrashed()->find(1);
if ($trashedPost) {
$trashedPost->restore();
}
// Permanently delete a post
$postToDeleteForever = Post::find(2);
if ($postToDeleteForever) {
$postToDeleteForever->forceDelete();
}
*/
}
How it works: Soft Deletes provide a way to logically 'delete' records by marking them with a timestamp in a `deleted_at` column, rather than truly removing them from the database. This allows you to easily restore them later. To enable it, use the `SoftDeletes` trait on your model and add a `deleted_at` column to your table. Eloquent queries will automatically exclude soft-deleted records. You can use methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` to interact with these records.