如何找到 laravel 模型路由绑定中预期的参数名称

How to find the parameter name expected in laravel model route binding

我有这样的路线

Route::get('/vcs-integrations/{vcs-provider}/authenticate','VcsIntegrationsController@authenticate');

我使用模型路由绑定来处理路由的方法如下

<?php

....
use App\Models\VcsProvider;
....

class VcsIntegrationsController extends Controller
{
  public function authenticate(VcsProvider $vcsProvider, Request $request)
    {
        ...
        // some logic
        ...
    }
}

当我尝试访问路由时,由于参数名称不匹配,我得到了 404。

那么,我怎么知道路由模型绑定中laravel期望的参数名称呢?

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

这意味着如果您希望隐式绑定起作用,您需要将路由参数命名为与您的变量相同的名称。由于您的变量名称是 vcsProvider,因此您的路线应该是:

Route::get('/vcs-integrations/{vcsProvider}/authenticate','VcsIntegrationsController@authenticate');

来自路由参数文档:

"Route parameters are always encased within {} braces and should consist of alphabetic characters, and may not contain a - character. Instead of using the - character, use an underscore (_)." - Laravel 7.x Docs - Routing - Route Parameters - Required Parameters

您应该能够在路由定义中将参数定义为 {vcs_provider},然后如果您愿意,可以在方法签名中使用 $vcs_provider 作为参数名称。如果您愿意,也可以不使用 _ 来命名它,但在命名时避免使用 -、连字符。

玩得开心,祝你好运。