How to Use Soft Delete in Eloquent: Laravel Guide
To use
soft delete in Eloquent, add the SoftDeletes trait to your model and include a deleted_at timestamp column in your database table. This marks records as deleted without removing them, allowing you to restore or permanently delete them later.Syntax
To enable soft deletes in an Eloquent model, you need to:
- Use the
SoftDeletestrait in your model class. - Add a
deleted_atcolumn of typetimestampornullable timestampto your database table.
This setup allows Eloquent to automatically exclude soft deleted records from query results.
php
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; protected $dates = ['deleted_at']; }
Example
This example shows how to soft delete a record, query soft deleted records, restore them, and permanently delete them.
php
<?php use App\Models\Post; // Soft delete a post $post = Post::find(1); $post->delete(); // Query only non-deleted posts $posts = Post::all(); // Query including soft deleted posts $allPosts = Post::withTrashed()->get(); // Query only soft deleted posts $trashedPosts = Post::onlyTrashed()->get(); // Restore a soft deleted post $post->restore(); // Permanently delete a post $post->forceDelete();
Output
No visible output; database records are marked with deleted_at timestamp or restored/removed accordingly.
Common Pitfalls
- Forgetting to add the
deleted_atcolumn in the database causes errors or soft delete to not work. - Not using
withTrashed()oronlyTrashed()when querying soft deleted records will exclude them by default. - Calling
delete()permanently removes records ifSoftDeletestrait is not used.
php
/* Wrong: No SoftDeletes trait, delete permanently removes record */ class Post extends Model {} $post = Post::find(1); $post->delete(); // Permanently deletes /* Right: Use SoftDeletes trait to enable soft delete */ use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; protected $dates = ['deleted_at']; } $post = Post::find(1); $post->delete(); // Marks deleted_at timestamp instead of deleting
Quick Reference
Summary tips for using soft delete in Eloquent:
- Add
SoftDeletestrait to your model. - Add
deleted_atnullable timestamp column to your table. - Use
delete()to soft delete,restore()to undo. - Use
withTrashed()oronlyTrashed()to query soft deleted records. - Use
forceDelete()to permanently remove records.
Key Takeaways
Add the SoftDeletes trait and deleted_at column to enable soft delete in Eloquent models.
Soft deleted records are excluded from queries unless you use withTrashed() or onlyTrashed().
Use delete() to soft delete, restore() to bring back, and forceDelete() to permanently remove records.
Always ensure your database table has a nullable deleted_at timestamp column.
Without the SoftDeletes trait, delete() permanently removes records instead of soft deleting.