1

I'm trying to make it so that I can have all routes inside of a group automatically use a domain parameter without having to specify it in views and whatnot. Here is an example of what I am looking for.

Route group code:

Route::group(['domain' => '{tenant_domain}.myapp.com', 'middleware' => 'tenant'], function () {

The tenant middleware handle:

public function handle($request, $next)
{
    session(['tenant_domain' => $request->route('tenant_domain')]);

    return $next($request);
}

So instead of having to use this code in all my views:

{{ route('login', ['tenant_domain' => session('tenant_domain')]) }}

I'd like to only use:

{{ route('login') }}

And then in the boot() method of RouteServiceProvider, have something like:

public function boot()
{
    if (isset(session('my_parameter'))) {
        Route::addParameter(['tenant_domain' => session('tenant_domain')]);
    }

    parent::boot();
}

How can I do this properly so it works?

kjdion84
  • 9,552
  • 8
  • 60
  • 87
  • I'd have the middleware do `config('tenant.domain', $request->route('tenant_domain'))` and just use `config('tenant.domain')` where you want to access the variable. – ceejayoz Apr 30 '17 at 21:47
  • How do I make it so I don't have to include `tenant_domain` as a parameter for the routes inside the group? I've tried using `$request->route()->forgetParameter('tenant_domain')` in the `tenant` middleware and it doesn't work. – kjdion84 Apr 30 '17 at 21:52
  • Ohhhhh, I understand the question better now. Sorry, I don't have an answer there. – ceejayoz Apr 30 '17 at 21:56

1 Answers1

0

Not sure if you automatically bind it to a route. However you can overwrite all Laravel helpers because it is checked if they exist before they are defined:

if (! function_exists('route')) { //etc }}

So you could rewrite the route function (originally located in Illuminate/Foundation/helpers.php with something like this:

/**
* Generate the URL to a named route.
*
* @param  string  $name
* @param  array   $parameters
* @param  bool    $absolute
* @return string
*/
function route($name, $parameters = [], $absolute = true)
{
    if (session()->has('tenant_domain'))) {
        $parameters = array_prepend($parameters, session()->get('tenant_domain'));
    }
    return app('url')->route($name, $parameters, $absolute);
} 

You can find how to add a custom helper in this thread.

Community
  • 1
  • 1
Björn
  • 5,696
  • 1
  • 24
  • 34
  • This is OK but then I still have to add `$tenant_domain` to all my controller methods...how can I avoid that? – kjdion84 Apr 30 '17 at 22:08
  • It appears the solution is to use your helper function as well as `forgetParameter` so it doesn't need to be injected into controller methods. Thank you. – kjdion84 Apr 30 '17 at 22:30
  • Ah very cool, didn't know about `forgetParameter`. So a middleware to do `$request->route()->forgetParameter('tenant_domain');`? – Björn May 01 '17 at 08:21