在 Laravel 中将参数传递给中间件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40975467/
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
Passing parameters to middleware in Laravel
提问by athene
Let's say I have a route pointing to middleware;
假设我有一条指向中间件的路由;
Route::get("/user/{id}", ['middleware' => 'auth', function ($id) {
}]);
And my middleware code is as follows:
我的中间件代码如下:
public function handle($request, Closure $next)
{
return $next($request);
}
If I want to use $id
in the middleware, how do I do that?
如果我想$id
在中间件中使用,我该怎么做?
回答by Saumya Rastogi
In you case you cannot pass $id
into the middleware.
在你的情况下,你不能$id
进入中间件。
Generally you can pass parameters to middleware via using :
symbol like this:
通常,您可以通过使用这样的:
符号将参数传递给中间件:
Route::get('user/{id}', ['middleware' => 'auth:owner', function ($id) {
// Your logic here...
}]);
And get the passed parameter into middleware method like this:
并将传递的参数放入中间件方法中,如下所示:
<?php
namespace App\Http\Middleware;
use Closure;
class Authentication
{
public function handle($request, Closure $next, $role)
{
if (auth()->check() && auth()->user()->hasRole($role)) {
return $next($request);
}
return redirect('login');
}
}
Note that the
handle()
method, which usually only takes a$request
and a$next closure
, has athird parameter
, which is our middleware parameter. If you passed in multiple parameters to your middleware call in the route definition, just add more parameters to your handle() method
请注意,
handle()
通常只接受 a$request
和 a的方法$next closure
有 athird parameter
,这是我们的中间件参数。如果您在路由定义中将多个参数传递给您的中间件调用,只需向您的 handle() 方法添加更多参数
Hope this helps!
希望这可以帮助!
回答by Amit Gupta
You can use one of the following method to access the route parameter in a middleware:
您可以使用以下方法之一访问中间件中的路由参数:
First Method
第一种方法
$request->route()->parameters();
$request->route()->parameters();
This method will return an array of all the parameters.
此方法将返回所有参数的数组。
Second Method
第二种方法
$request->route('parameter_name');
$request->route('parameter_name');
Here parameter_name
refers to what you called the parameter in the route.
这里parameter_name
指的是你在路由中调用的参数。