Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JasperK's avatar

Remove subdomain parameter in Controllers?

Hi, I'm doing subdomain routing, and I wanna know if there is a way to avoid adding the first parameter, where the subdomain is stored?

public function find($path){
return $path;
}
# Output: 'subdomain name'

public function find($account, $path){
return $path;
}
#Output: correct path. 


Route::group(['domain' => '{account}.mywebsite.com', 'middleware' => 'subdomain'], function () {

});

It's annoying to implement it for each existing Controller.

namespace App\Http\Middleware;

class SubdomainMiddleware
{
    public function handle($request, Closure $next)
    {
        $subdomain = $request->route()->account;

        if(! in_array($subdomain, config('app.websites'))) {
            return abort(404);
        }

        // I'm doing some things for the subdomain over here

        return $next($request);
    }
}
0 likes
9 replies
JasperK's avatar

More like skipping it at all as a first parameter for a function in a Controller. If I decide later on, to remove the subdomain or wanna re-use the Controller without being in a subdomain, it isn't possible in this way.

pmall's avatar

So you use this subdomain info in a middleware I guess ?

JasperK's avatar

Yes @pmall - I'm doing all the stuff I want over there for the subdomain routing. So it's not needed anymore in the Controllers of course. Edited startpost with my Middleware.

StepToMe's avatar

@pmall Your solution works great. There is one case where it doesn't work for me, and that is when calling redirect()->action() in a controller method.

First, all routes are in a domain group.

Route::middleware(['some_middleware'])->domain('{subdomain}' .website.com)->group(function () {
    // .. All routes
}   );

In some_middleware I have

public function handle($request, Closure $next) {

    // .. 

    $request->route()->forgetParameter('subdomain');

    return $next($request);
}

Then where it doesn't work:

public function process()
{
    // ...

    redirect()->action('SimpleController@show', ['simple' => $id]);
}


This only works if I explicitly pass in the variable.

public function process()
{
    // ...

    redirect()->action('SimpleController@show', ['subdomain' => 'some_subdomain', 'simple' => $id]);
}

Do you (or anyone else) have suggestions on how to tackle this? :) Thanks!

basvandertogt's avatar

$request->route() returns null in Laravel 5.5. Any idea?

1 like

Please or to participate in this conversation.