partenit
3/14/2013 - 1:16 AM

Laravel redirect to last visited page if not logged in

Laravel redirect to last visited page if not logged in

Route::filter('auth', function()
{
  if (Auth::guest())
	{
		// Save the attempted URL
		Session::put('pre_login_url', URL::current());

		// Redirect to login
		return Redirect::to('login');
	}
});

Route::post('login', function()
{
  // Get the POST data
	$data = array(
		'username'      => Input::get('username'),
		'password'      => Input::get('password')
	);

	// Attempt Authentication
	if ( Auth::attempt($data) )
	{
		// If user attempted to access specific URL before logging in
		if ( Session::has('pre_login_url') )
		{
			$url = Session::get('pre_login_url');
			Session::forget('pre_login_url');
			return Redirect::to($url);
		}
		else
			return Redirect::to('admin');
	}
	else
	{
		return Redirect::to('login')->with('login_errors', true);
	}
});