In Laravel, when you use implicit route model binding, Laravel will automatically fetch the model instance that corresponds to the route parameter.
use App\Models\User;
Route::get('/users/{user}', function (User $user) {
return $user->email;
});
If you visit /users/5
, Laravel will do something like:
$user = User::findOrFail(5);
and then pass that $user
to your closure.
SoftDeletes
trait, it isn’t actually removed from the database when you call $user->delete()
.deleted_at
column gets filled with a timestamp.find()
or first()
.So if a User
with ID 5
is soft deleted, /users/5
will normally give you a 404 Not Found, because Laravel won’t include trashed models in the binding query.
withTrashed()
When you add:
Route::get('/users/{user}', function (User $user) {
return $user->email;
})->withTrashed();
You’re telling Laravel:
“When performing route model binding for this route, also include soft-deleted (trashed) models.”
So now:
/users/5
refers to a soft-deleted user, Laravel will still retrieve it and pass it into the route closure.withTrashed()
, the same request would throw a 404.âś… In short:
withTrashed()
allows binding to include trashed models as well.Subscribe to get the latest posts sent to your email.