Laravel 中间件获取路由参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35762302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel middleware get route parameter
提问by KIDJourney
I am coding some thing like 'school club manage system' and meet some problem on rights authorization of resource .
我正在编写诸如“学校俱乐部管理系统”之类的东西,并且遇到了资源权限授权方面的一些问题。
Suppose there are club
, and club
have manager , and i want to check if the user is a manager of club
before he can manage it with a middleware.
假设有club
,并且club
有 manager ,我想检查用户是否是 manager ,club
然后他才能使用中间件管理它。
Using laravel 5.2
使用 Laravel 5.2
My router
looks like that :
我的 router
样子:
Route::resource('club', 'ClubController');
Route::resource('club', 'ClubController');
The middleware I create looks like that :
我创建的中间件看起来像这样:
public function handle($request, Closure $next)
{
if (!Auth::check()){
// ask user to login
}
$club = Club::findOrFail($request->input('club'));
$user = Auth::user();
if (!$club->managers->contains($user)){
//tell user your are not manager .
}
return $next($request);
}
But I failed to get the id of club from requests
.
但是我没能从requests
.
How can I solve the problem ?
我该如何解决问题?
Thanks in advance .
提前致谢 。
回答by Shyam Achuthan
if you are looking for the url parameters the best way of getting that from the resource routes in laravel 5.2 inside the middleware is below. Lets say you want to get id parameter form url club/edit/{id}
如果您正在寻找 url 参数,那么从中间件内的 laravel 5.2 中的资源路由中获取该参数的最佳方法如下。假设您想从 url club/edit/{id} 获取 id 参数
$request->route()->parameter('id');
回答by Mostafa Soufi
A shorter syntax is:
较短的语法是:
$request->route('parameter_name');
回答by KIDJourney
Woops , I found the ans after checking dd($requests)
.
Woops,我在检查后找到了答案dd($requests)
。
I can use $requests->club
to get parameter .
我可以$requests->club
用来获取参数。
Thanks everyone.
谢谢大家。
回答by Joyal
I am on Laravel 5.5 and
我在 Laravel 5.5 和
dd($request->route()->parameter('id'));
dd($request->route('id'));
worked for me
对我来说有效