Laravel 4: Redirect to the intended url after login

The best way to redirect a user who is not logged in is to use the ‘Redirect::guest(..)’ method. This method will store the intended url in the session of the user. After logging in he can be be redirected back to the intended url via ‘Redirect:intended(..)’.

See example below.

In the example below the user hits the url ‘mydomain/administrator’, the ‘admin_auth’ filter checks whether the user is logged in. If so the user will be brought to the ‘admin.index’ view, otherwise he will be redirected via the ‘Redirect::guest(..)’ method to the login screen.

After posting the data to the controller (postLogin method) it will check whether the user is allowed to login and if so he will be redirected to the intended url which lives in the session. In this case ‘mydomain/administrator’. Note also the ‘fallback’ parameter. This one will be used when no URL is found in the session.

Routes.php:

Route::group(array('prefix' => 'administrator', 'before' => 'admin_auth'), function()
{
    Route::get('/', function()
    {
        return View::make('admin.index');
    });
});

Route::filter('admin_auth', function()
{
    if (!Sentry::check())
    {
        // if not logged in, redirect to login
        // Stores the intended url in the session.
        return Redirect::guest('user/login');
    }

    if (!Sentry::getUser()->hasAccess('admin'))
    {
        // has no access
        return Response::make('Access Forbidden', '403');
    }
});

And in your controller:

  public function postLogin()
    {
      //Check whether he is allowed to login.. code removed...
      
      //Eventually login was succesful, redirect to the intended url.
      //If not found, go to 'fallback'
      return Redirect::intended('fallback');
    }

2 comments to Laravel 4: Redirect to the intended url after login

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>