The solution is to dynamically register middleware in the kernel. First write your middleware, for example:
<?php namespace HynMe\MultiTenant\Middleware; use App; use Closure; use Illuminate\Contracts\Routing\Middleware; class HostnameMiddleware implements Middleware { public function handle($request, Closure $next) { /* @var \HynMe\MultiTenant\Models\Hostname */ $hostname = App::make('HynMe\Tenant\Hostname'); if(!is_null($redirect = $hostname->redirectActionRequired())) return $redirect; return $next($request); } }
Now that your service provider uses the following code in the boot() method to add this middleware to the kernel:
$this->app->make('Illuminate\Contracts\Http\Kernel')->prependMiddleware('HynMe\MultiTenant\Middleware\HostnameMiddleware');
To respond to the redirectActionRequired() method in the hostname object:
/** * Identifies whether a redirect is required for this hostname * @return \Illuminate\Http\RedirectResponse|null */ public function redirectActionRequired() { // force to new hostname if($this->redirect_to) return $this->redirectToHostname->redirectActionRequired(); // @todo also add ssl check once ssl certificates are support if($this->prefer_https && !Request::secure()) return redirect()->secure(Request::path()); // if default hostname is loaded and this is not the default hostname if(Request::getHttpHost() != $this->hostname) return redirect()->away("http://{$this->hostname}/" . (Request::path() == '/' ? null : Request::path())); return null; }
If you need to dynamically register routeMiddleware, use the following in your service provider:
$this->app['router']->middleware('shortname', Vendor\Some\Class::class);
Please add comments if you have questions about this implementation.
Luceos
source share