Accessing Soft Deleted Models in Laravel Routes

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.

Now, about Soft Deletes

  • If a model uses the SoftDeletes trait, it isn’t actually removed from the database when you call $user->delete().
  • Instead, its deleted_at column gets filled with a timestamp.
  • By default, Laravel excludes soft deleted rows from queries like 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.

Using 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:

  • If /users/5 refers to a soft-deleted user, Laravel will still retrieve it and pass it into the route closure.
  • Without withTrashed(), the same request would throw a 404.

âś… In short:

  • Normal binding ignores trashed models.
  • withTrashed() allows binding to include trashed models as well.


Discover more from MountAviary

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *