我想知道如何使用控制器构造函数设置中间件,并在我的路由文件中成功完成后引用中间件参数。
我在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()
当然我做错了 - 我无法在文档中看到如何做到这一点并且阅读源代码没有帮助,但也许我忽略了一些东西。所以我想知道什么是正确的方式,甚至可能吗?任何帮助都将非常感谢,谢谢!
答案 0 :(得分:2)
您使用错误的语法从控制器构造函数设置中间件。
首先,您必须使用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']]);
}
答案 1 :(得分:1)
试试这个
function __construct()
{
$this->middleware('user-type:param1,param2', ['only' => ['show', 'update']]);
}