[英]Laravel 4: Add a filter to a route a pass it a controller
How to you add a filter to a route and pass a controller to it?. 如何在路由中添加过滤器并将控制器传递给它?
In Laravel's doc they said that you can add a filter to a route like this: 在Laravel的文档中,他们说你可以为这样的路线添加一个过滤器:
Route::get('/', array('before' => 'auth', function()
{
return 'Not Authorized';
}));
But I need to pass a controller, like this: 但我需要传递一个控制器,如下所示:
Route::get('/', array('before' => 'auth', 'HomeController@index'));
But I get this error when I do it like that: 但是当我这样做时,我得到了这个错误:
call_user_func_array() expects parameter 1 to be a valid callback, no array or string given
Any idea? 任何想法?
You should pass the controller function with uses
key, So replace, 您应该
uses
键传递控制器功能,所以替换,
Route::get('/', array('before' => 'auth', 'HomeController@index'));
With, 随着,
Route::get('/', array('as' => 'home', 'before' => 'auth', 'uses' => 'HomeController@index'));
And there should be a route for login to process the auth
filter like this. 并且应该有一个登录路由来处理这样的
auth
过滤器。
Route::get('login', function()
{
if(Auth::user()) {
return Redirect::to('/');
}
return View::make('login');
});
Wanted to add another solution to your problem. 想为您的问题添加另一种解决方案。
You can also use this, which in my opinion feels more readable. 你也可以使用它,在我看来,它更具可读性。
Route::get('/', 'HomeController@index')->before('auth');
You only need to use "as" and "uses" if you're in need of named routes, eg. 如果您需要命名路线,则只需使用“as”和“uses”,例如。 for a Form route.
对于表单路由。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.