Laravel 4: add a filter to the route, skip its controller

How to add a filter to a route and pass a controller to it ?.

In a Laravel document, they said that you can add a filter to the following route:

Route::get('/', array('before' => 'auth', function()
{
     return 'Not Authorized';
}));

But I need to pass the controller, for example:

Route::get('/', array('before' => 'auth', 'HomeController@index'));

But I get this error when I do it like this:

call_user_func_array() expects parameter 1 to be a valid callback, no array or string given

Any idea?

+4
source share
2 answers

You must pass the controller function with the key uses, so replace

Route::get('/', array('before' => 'auth', 'HomeController@index'));

FROM

Route::get('/', array('as' => 'home', 'before' => 'auth', 'uses' => 'HomeController@index'));

And to enter the system for the filter there authmust be a route for entry.

Route::get('login', function()
{
   if(Auth::user()) {
      return Redirect::to('/');
   }

   return View::make('login');
});
+10
source

Need to add another solution to your problem.

You can also use this, which, in my opinion, looks more readable.

Route::get('/', 'HomeController@index')->before('auth');

"" "", , . .

+5

All Articles