While building multi-tenancy packages for Laravel 5 I had to find out how to add middleware dynamically from code. In comparison to this question on SO I do not want to touch the Http/Kernel definitions.
During application initialization I check whether the requested hostname is known in the database and whether this hostname requires a redirect to a primary hostname or ssl.
Because you don't want to touch the Http/Kernel
as a package, we need to use the service provider.
Requirements:
- dynamically add middleware without touching Http/Kernel
- use service provider and response object instead of "hacks"
The solution is to dynamically register the middleware in the kernel. First write your middleware, for instance:
Now in your service provider use the following code in the
boot()
method to add this middleware to the Kernel:To answer what
redirectActionRequired()
method does in the hostname object:If you need to dynamically register routeMiddleware use the following in your service provider;
Please add comments if you have questions about this implementation.