Last Updated: February 25, 2016
·
4.991K
· buildcomplete

Using Redirect::intendeed with authentication in laravel

New to laravel, I ran into a problem of using Redirect::intendeed during the authentication process.

My intention was to have a filter, that ensures only log'd in users can use access the protected area, and after login land on the page with the link the user originally typed in.

as was the case, it was very simple to get working, I found the sollution in the laravel forum:
Link
but im posting it here, ( so I can find it myself again :) )

Route::filter('auth.admin', function()
{
  if (Auth::check() == false)
  {
  // Notice that im using Redirect::guest instead of Redirect::to, 
  // this is to make the Redirect::intendeed work later on.
    return Redirect::guest('login');
  }
});

then in my login handling, i use Redirect::intendeed

public function postLogin()
{
    // Get all the inputs
    $userdata = array(
        'email' => Input::get('email'),
        'password' => Input::get('password')
    );

    // Declare the rules for the form validation.
    $rules = array(
        'email'  => 'Required',
        'password'  => 'Required'
    );

    // Validate the inputs.
    $validator = Validator::make($userdata, $rules);

    // Check if the form validates with success.
    if ($validator->passes())
    {
        // Try to log the user in.
        if (Auth::attempt($userdata))
        {
            // Redirect to intended page, 
            // notice this only works if we redirected to the login page using Redirect::guest(...)
            return Redirect::intended('/')->with('success', 'You have logged in successfully');
        }
        else
        {
            // Redirect to the login page.
            return Redirect::to('login')->withErrors(array('password' => 'Password invalid'))->withInput(Input::except('password'));
        }
    }

    // Something went wrong.
    return Redirect::to('login')->withErrors($validator)->withInput(Input::except('password'));
}

1 Response
Add your response

Great post, I didn't realize that you needed to Redirect::guest in order to use the intended route!

over 1 year ago ·