Search code examples
phplaravelauthenticationbefore-filter

Laravel 4.2 | construct beforeFilter - auth check


I've got this code:

function __construct() {
  $this->beforeFilter('auth');

  if (Auth::user()->hasRole('A')) {
    return \Redirect::route('B')->send();
  }
}

Route::filter('auth', function()
{
    if (Auth::guest())
    {
        if (Request::ajax())
        {
            return Response::make('Unauthorized', 401);
        }
        else
        {
            return Redirect::guest('auth/login');
            die();
        }
    }
});

And the result is this error:

Call to a member function hasRole() on null

The auth filter should redirect me automatically to auth page. But it doesn't do that until it finished the all function.

Any suggestions?


Solution

  • Well, this is the solution:

    function __construct() 
    {
      if ($this->beforeFilter('auth')) {
        if (Auth::user()->hasRole('A')) {
          return \Redirect::route('B')->send();
        }
      }
    }