Skip to content

Instantly share code, notes, and snippets.

@salipro4ever
Created May 6, 2019 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salipro4ever/dacf69b28eda846c8ecf505902a443ea to your computer and use it in GitHub Desktop.
Save salipro4ever/dacf69b28eda846c8ecf505902a443ea to your computer and use it in GitHub Desktop.
subdomain map to subdirectory route in existing Laravel

I serve multiple subdomains with Laravel with this code here:

RouteServiceProvider.php

  protected function mapSubdomainRoutes()
  {
    Route::group([
      'namespace' => $this->namespace,
      'domain' => '{subdomain}.affekt.de',
    ], function () {
      require base_path('routes/web.php');
    });
  }

But watch out you have an new argument then for your controllers. It's $subdomain. I remove this argument with a custom middleware. Because I don't want to add $subdomain argument to all my controllers.

$route->forgetParameter('subdomain'); will remove it.

<?php

namespace App\Http\Middleware;

use Closure;

class RemoveSubdomainArgs
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $route = $request->route();
        $route->forgetParameter('subdomain');
        return $next($request);
    }
}

Don't forget to add the new RemoveSubdomainArgs middleware to your HTTP kernel.

@seatechdev
Copy link

seatechdev commented Oct 20, 2021

are you supposed to put this code in the main domain or subdomain's providers and middleware? I followed your instructions on this page and here https://laracasts.com/discuss/channels/servers/subdomain-map-to-subdirectory-route-in-existing-laravel-project
But they didn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment