如何获取和传递URL参数到Laravel 5.1中的类?

问题描述:

在Laravel 5.1的路由文档中,似乎没有告诉如何获取和传递URL参数到类.那么我们应该如何从URL获取路由参数呢?

In Laravel 5.1's Routing documentation, it seems it doesn't tell how to get and pass URL parameters to classes. So how should we get route parameters from URLs?

例如,使用 RESTful资源控制器来更新用户的个人资料,您的应用程序PATCH(实际上是 POST )发送到:

For example, using RESTful Resource Controller to update a user's profile, your app PATCHes (POST actually) to:

/profile/10

/profile/10

因此,当在UpdateUserRequest的rules()方法中时,如何从URL中获取ID 10,以验证用户的电子邮件是否与其他用户一样唯一?

So when inside the rules() method in UpdateUserRequest, how do you get the id 10 from the URL to validate user's email as unique from other users like this?

public fnction rules()
{
    return [ 'email' => 'uniqie:users,email,'.$id ]
}

如果我dd(Request :: all())不包含'id'='10'. 请帮忙.谢谢!

If i dd(Request::all()), it does not contain 'id' = '10'. PLease help. Thank you!

更新

表单请求验证文档中,它表示Laravel授予了您可以通过以下方式访问路由/URL参数:

In the Form Request Validation doc, it said that Laravel grants you to access route/URL parameters with:

$this->route('id');

但是它仅适用于非资源路由,例如:

But it only works on non-resource routes like:

Route::post('users/{id}', 'UsersController@store');

它不适用于:

Route::resource('users', 'UserController');

那么如何从资源路由中获取和传递路由参数?

So how do you get and pass route parameters from resource routes?

将ID返回给UpdateUserRequest:

Return id to UpdateUserRequest:

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

因为Route:resource将为您提供/users/{users}而不是/users/{id}.

because Route:resource will give you /users/{users} instead of /users/{id}.

您可以通过命令行使用此命令:

you can use this command via command line :

php artisan route:list

帮助您列出所有路线.