简体   繁体   English

Laravel 5通配符子域+路由模型绑定

[英]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 在RouteServiceProvider上

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

and on the UserController show method: 并在UserController上显示方法:

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: 这是因为subdomain参数传递给控制器​​方法,我必须像这样更改它们:

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. 我只是不想将subdomain参数添加到我的应用程序中的每个控制器方法,因为我不会对它做任何事情。 I use the subdomain parameter in a middleware to do some configuration changes. 我在中间件中使用subdomain参数来进行一些配置更改。

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 在你的控制器功能中,你可以忽略$ dubdomain,如果你不使用它,并确保你输入像这样的用户

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. 要避免需要子域,可以指定Laravel忘记该路由参数。

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. 但是,我强烈建议将该过程转移到中间件中,因为它不适合将它放在routes文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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