Laravel 5 - 无法访问路由内的 ID 变量

Laravel 5 - Unable to access the ID variable within the route

我当前的设置:

控制器:

public function showGeneralPage($id, ShowClinicFormRequest $request)
{
    return View::make('clinic.general', ['clinic' => Clinic::where('id', $id)
        ->first()]);
}

ShowClinicFormRequest:

public function authorize()
{
    $clinicId = $this->route('clinic');

    return Clinic::where('id', $clinicId)
    ->where('user_id', Auth::id())
    ->exists();
}

路线:

Route::get('clinic/{id}/general', 'ClinicController@showGeneralPage

当试图点击页面 - <a href="{{ url('/clinic/general') }}">General</a> 时,出现 forbidden 错误。

老实说,我什至不得不在 URL 内出示基于诊所的 ID 并不过分担心,但我看不到其他解决方法吗?任何帮助将不胜感激。非常感谢。

这里有两个问题。首先,您必须在生成 URL 时传递 id。假设变量 $id:

url('clinic/'.$id.'/general')

其次,您正在尝试检索参数 clinic,但它实际上被称为 id
将其更改为:

$clinicId = $this->route('id');

你可以试试这个(不过我发现了三个问题):

$id = $this->route()->parameter('id'); // $this->route('id') works as well

另外在生成URI的时候需要传入id,例如:

{{ url("clinic/{$id}/general") }} // $id may have some value, i.e: 10

此外,您需要更改此处参数的顺序:

 public function showGeneralPage($id, ShowClinicFormRequest $request)

应该是:

 public function showGeneralPage(ShowClinicFormRequest $request, $id)

注意:当使用 Method Injection 时,将您的方法参数放在类型提示依赖注入参数之后。