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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:20:05  来源:igfitidea点击:

Laravel middleware get route parameter

phplaravel

提问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 clubhave manager , and i want to check if the user is a manager of clubbefore he can manage it with a middleware.

假设有club,并且club有 manager ,我想检查用户是否是 manager ,club然后他才能使用中间件管理它。

Using laravel 5.2

使用 Laravel 5.2

My routerlooks 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->clubto 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

对我来说有效