简体   繁体   中英

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:

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,

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.

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. for a Form route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM