我想知道如何使用控制器构造函数和引用中间件参数来设置中间件,因为我已经在我的路由文件中成功地完成了。
在routes.php:
Route::group(['middleware' => 'user-type:user'], function () {
// routes
});
现在我想在控制器构造函数中这样做,但我遇到了一些问题…
public function __construct()
{
$this->middleware = 'event-is-active:voting';
}
当我访问一个应用了上面的链接时,我得到以下错误:
ErrorException in ControllerDispatcher.php line 127:
Invalid argument supplied for foreach()
当然我做错了——我看不出如何在文档中做到这一点,阅读源代码也没有帮助,但也许我忽略了一些东西。所以我想知道什么是正确的方法,这可能吗?任何帮助将是最感激的,谢谢!
从控制器构造函数设置中间件使用了错误的语法。
首先你必须使用laravel 5.1来使用中间件参数。
现在你只能在构造函数中设置控制器中的中间件。
function __construct()
{
$this->middleware('event-is-active:voting');//this will applies to all methods of your controller
$this->middleware('event-is-active:voting', ['only' => ['show', 'update']]);//this will applies only show,update methods of your controller
}
请注意,在上面的代码显示和更新是示例的名称。你必须写你在控制器中使用的实际名称。
假设您正在使用1. getShowUser (userId美元)2. postUpdateUser ($ userId)
,你必须在这些方法中应用中间件,如下所述:
function __construct()
{
$this->middleware('event-is-active:voting', ['only' => ['getShowUser', 'postUpdateUser']]);
}
试试这个
function __construct()
{
$this->middleware('user-type:param1,param2', ['only' => ['show', 'update']]);
}