Laravel
Intermediate
Eloquent & Routing
· 6 min read
Laravel Soft Deletes
Lesson 22 of 33 in the Laravel learning path.
How do I hide a lesson without removing the row?
Soft delete sets deleted_at instead of removing the row. Normal queries skip those rows.
An instructor can undo a removal. Enrollments still have a lesson id to point at.
Syntax & Parameters
use SoftDeletes; $lesson->delete();
Example
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Lesson extends Model
{
use SoftDeletes;
protected $fillable = ['title', 'slug', 'track'];
}
function archive(Lesson $lesson): void
{
$lesson->delete();
}
function restoreLesson(int $id): void
{
$lesson = Lesson::withTrashed()->findOrFail($id);
$lesson->restore();
}
Expected Output
Archived lessons vanish from the catalog query. An admin restore brings the same id back.
Line-by-Line Walkthrough
- The model uses the SoftDeletes trait.
- The table needs a nullable deleted_at timestamp.
- delete sets deleted_at. It does not run a SQL DELETE.
- Lesson::query() hides archived rows.
- withTrashed includes them when an admin must restore.
- findOrFail still 404s if the id never existed.
- restore clears deleted_at.
- forceDelete is the real delete, and it should be rare.
Common Pitfalls & Security
Watch the failure mode, not only the happy path.
- Forgetting the deleted_at column makes delete throw.
- Unique slugs still collide with a soft-deleted row unless the unique index accounts for it.
- A foreign key does not know about soft deletes. Children can point at a hidden parent.
- withTrashed on a public route exposes removed courses.
Best Practices & Modern Standards
Use soft deletes when undo matters. Add deleted_at in a migration.
Keep public queries on the default scope. Use withTrashed only in the admin restore path.
Real-World Use
Removing a lesson hides it from students. Support can restore it the same day without recreating enrollments.
Frequently Asked Questions
Does delete remove the row?
Not with this trait. It sets deleted_at.
How do I include archived rows?
Lesson::withTrashed() or onlyTrashed().
How do I really delete?
forceDelete(). Use it only when the row must go.
Do I need a migration?
Yes. Add a nullable deleted_at timestamp.