OiO.lk Blog PHP How to run middleware in Laravel even when route model binding fails?
PHP

How to run middleware in Laravel even when route model binding fails?


I am having an issue in building a feature for my app in Laravel, because of its strange implicit route model binding logic.

I have some routes configured for an admin panel with implicitly bound models. An example follows:

Route::get('/admin/books/{book}', BooksController);

I obviously also have a global middleware for all admin routes that checks whether the user is authenticated as an admin and then route him to the sign in page if he isn’t one.

class AuthenticateAdmin
{
   public function handle(Request $request, Closure $next): Response
   {
      dump('inside admin auth middleware');
      if (! Auth::user()?->is_admin) {
         return to_route('admin.signin');
      }
      return $next($request);
   }
}

The issue I am facing is that if I visit a non-existent route, for example /admin/books-non-existent, I get the correct redirection since the middleware does fire up. That is, I get the dump message.

However, if I visit an existent route but where the model binding fails, for example /admin/books/xyz, the middleware doesn’t run at all!! I don’t get any dump message.

How to get the middleware to run also when the route model binding fails?



You need to sign in to view this answers

Exit mobile version