Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
arielcr Avatar asked Dec 06 '22 05:12

arielcr


1 Answers

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');
});
like image 167
Anshad Vattapoyil Avatar answered Dec 25 '22 07:12

Anshad Vattapoyil