PHP
Gracefully Handle Record Deletion with Laravel Eloquent Soft Deletes
Implement a robust soft deletion strategy in your Laravel application, allowing records to be logically deleted and easily restored without data loss.
// 1. In your migration file (e.g., create_posts_table.php):
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();
$table->softDeletes(); // Adds 'deleted_at' column
});
// 2. In your Eloquent Model (e.g., App\Models\Post.php):
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes; // Import the trait
class Post extends Model
{
use SoftDeletes; // Use the SoftDeletes trait
protected $fillable = ['title', 'body'];
}
// 3. Usage examples in a Controller or elsewhere:
use App\Models\Post;
// Delete a post (it will be soft deleted)
$post = Post::find(1);
$post->delete();
// 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
$trashedPosts = Post::onlyTrashed()->get();
// Restore a soft deleted post
$trashedPost = Post::withTrashed()->find(1);
if ($trashedPost) {
$trashedPost->restore();
}
// Permanently delete a post (force delete)
$postToDeletePermanently = Post::withTrashed()->find(2);
if ($postToDeletePermanently) {
$postToDeletePermanently->forceDelete();
}
How it works: This snippet illustrates how to implement soft deletes in Laravel using the `SoftDeletes` trait. By adding a `deleted_at` column in your migration and using the trait in your model, records are not physically removed from the database when `delete()` is called. Instead, the `deleted_at` timestamp is set. Eloquent queries will automatically exclude soft-deleted records. Methods like `withTrashed()`, `onlyTrashed()`, `restore()`, and `forceDelete()` provide full control over soft-deleted items.