简体   繁体   中英

Laravel 5 wildcard subdomain + route model binding

So when you define a resource controller in a wildcard subdomain group route similar to this:

Route::group(array('domain' => '{subdomain}.example.com'), function() {
  Route::resource('users', 'UserController');
});

on RouteServiceProvider

$router->model('user', 'App\User');

and on the UserController show method:

public function show($user)
{
    return $user;
}

what i get is the subdomain name instead of the user resource. This is because the subdomain parameter is passed to controller methods and i would have to change them like this:

public function show($subdomain, $user)
{
    return $user;
}

I simply don't want to add the subdomain parameter to each and every controller method in my app because i am not going to do anything with it. I use the subdomain parameter in a middleware to do some configuration changes.

How can i do it so the subdomain doesn't get passed to controllers as parameter?

In your controller function you can ignore the $dubdomain if you do not use it and make sure you typehint the User like this

public function show(User $user)
{
    return $user;
}

I'm aware that this question is somewhat old (and potentially stale) although I stumbled across this post when searching for an answer to another route model binding question.

To avoid requiring the subdomain, you can specify that Laravel forgets that route parameter.

You could either do this in a middleware (which checks for the subdomain too), like so:

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

Alternatively, using your code snippet, it would look something along the lines of this:

Route::group(array('domain' => '{subdomain}.example.com'), function() {
  Route::forgetParameter('subdomain');
  Route::resource('users', 'UserController');
});

However, I'd strongly recommend that the process is moved into a middleware, as it doesn't feel right putting that in the routes file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM