Laravel 5.6中的“绑定”中间件有什么作用?

时间:2018-07-31 11:49:07

标签: laravel laravel-5 middleware laravel-middleware

按照标题。 Laravel 5.6中的默认api中间件在Kernel.php中列为:

protected $middlewareGroups = [
    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

对于外行对bindings所做的事情的解释,我将不胜感激。

它使用具有SubstituteBindings方法的handle类:

public function handle($request, Closure $next)
{
    $this->router->substituteBindings($route = $request->route());
    $this->router->substituteImplicitBindings($route);
    return $next($request);
}

尽管我仍然不了解它的作用。

2 个答案:

答案 0 :(得分:5)

我有同样的问题,并且能够找到这个问题:

  

“路由模型绑定现在使用中间件完成。所有   应用程序应添加   照亮\ Routing \ Middleware \ Substitute绑定到您的Web   您的app / Http / Kernel.php文件中的中间件组:

     

\ Illuminate \ Routing \ Middleware \ SubstituteBindings :: class,

     

您还应该注册路由中间件以进行绑定替换   在HTTP内核的$ routeMiddleware属性中:

     

'绑定'=>   \ Illuminate \ Routing \ Middleware \ SubstituteBindings :: class,...“

可在此页面上找到-https://laravel.com/docs/5.3/upgrade

以上答案最初来自此来源-https://stackoverflow.com/a/47784205/3089840

在我看来,bindings中间件只是\Illuminate\Routing\Middleware\SubstituteBindings::class的快捷术语-如果正确,我不确定Laravel为什么在两个版本中都没有使用相同的术语webapi中的Kernel.php个数组。在\Illuminate\Routing\Middleware\SubstituteBindings::class数组中使用web和在bindings数组中使用api似乎有点矛盾和困惑。

答案 1 :(得分:0)

我认为您要的是这个https://laravel.com/docs/5.7/routing#route-model-binding

Route::get('api/users/{user}', function (App\User $user) {
    return $user->email;
});

它立即绑定用户模型。