Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3: Use auth/middleware on custom error page

The problem

When displaying HTTP error pages (404, 500 and so on), I want to keep the standard design of my current project, including header and footer. My project also includes a registration system. When a user is logged in and receives an error message, he will be redirected to the corresponding error page, but Laravel does not recognize that the user is logged in. That's because custom error pages (located in resources/views/errors/{code}.blade.php don't run through the normal web middleware (for some reasons).

This behavior was already reported a few times, but no sufficient answer was provided. A hacky solution is to set the StartSession middleware to be applied on every request, but this isn't sufficient in my case.

How can I use the Auth/Session middleware on custom error pages anyway?

Solutions that do not fit

  • I don't want to add the StartSession middleware (or any other) to every request

Related questions and links

  • Laravel Auth in error pages, Laravel 5.0 custom 404 does not use middleware -> Solution is not wanted
  • Laravel 5.2 Auth::check() on exception pages (layouts) No good solution
  • A GitHub issue I opened, because I think that this behavior is not intentional
like image 346
manniL Avatar asked Jan 07 '17 01:01

manniL


1 Answers

In coherence with the discussion around the github issue I've opened, here are the two best practices:

  1. Adding the StartSession middleware to the global middleware list is a good pratice, as long as your app doesn't have an API or similar
  2. In the second case, you can query the needed Frontend elements that are influenced by the session (e.g. login/register or profile buttons) by using jQuery and an AJAX call. So you are calling a route where middleware is applied and getting therefore the correct elements. A good example can be found in the GitHub issue I've linked.
like image 168
manniL Avatar answered Oct 17 '22 17:10

manniL