4

I have all my routes in a domain group but I would like to avoid having the domain as a parameter in each controller method.

So I would like to avoid having this everywhere:

public function show($domain, $id) {}

and would like to just keep it as

public function show($id) {}

I was able to partially make it work with $request->route()->forgetParameter('subdomain') placed in a middleware but it doesn't work in the case of calling redirect()->action('SomeController@show') from a controller method.


Here are some more details:

First, all routes are in a domain group.

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

    // .. All routes

}   );

Then, in some_middleware I have

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

    // .. 

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

    return $next($request);
}

Then where it doesn't work:

class SomeController {

    public function process()
    {
        // ...

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

The error I'm getting is:

Missing required parameters for [Route: ] [URI: simples/{simple}].

This only works if I explicitly pass in the subdomain variable.

class SomeController {

    public function process()
    {
        // ...

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

Can anyone suggest a "fix" for this? Thanks in advance :)

Denitsa
  • 141
  • 9

2 Answers2

2

With Laravel 5.5+, you can use URL::defaults to set request-wide values for things like the route helper.

https://laravel.com/docs/5.6/urls#default-values

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

    // .. 
    $subdomain = $request->route('subdomain');

    URL::defaults(['subdomain' => $subdomain]);

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

    return $next($request);
}
anderly
  • 727
  • 7
  • 16
0

You could create a wrapper helper for the action() helper:

if (! function_exists('actionSub')) {
    function actionSub($name, $parameters)
    {
        return action($name, $parameters + ['subdomain' => request()->route('subdomain')]);
    }
}

Then use it:

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

If someone has a more elegant solution for this, it will be great to see it.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279