How to Redirect back to Previous URL After Login in Laravel

820 views 9 months ago Laravel

Laravel has many useful features which makes web application development easy and fast. Laravel also provides default login system. But there is one thing we need to do is to redirect back to the previous page after successful login.

In this article we will show you how to change redirect back to previous url after success login. This is useful when login is required like feedback or comment or like in page. Therefore it is important that, user redirect back to that page.

In that case, there are two ways we can do it. One is Laravel provides inbuilt intended() method to redirect back to previous url.

/**
 * Show the application loginprocess.
 *
 * @return \Illuminate\Http\Response
 */
public function loginPost()
{
    if ($this->auth->attempt([
        'email' => Input::get('email'),
        'password' => Input::get('password')
    ])) {
        return Redirect::intended();
    } else {
        return back();
    }
}

The above method sometimes don't work properly. So the other method is we can do it by using Laravel Session. This will work perfect in all way.

/**
 * Show the application login page.
 *
 */
public function login()
{
    Session::put('previous_url', URL::previous());
    return view('login');
}
/**
 * Show the application loginprocess.
 *
 * @return \Illuminate\Http\Response
 */
public function loginPost()
{
    if ($this->auth->attempt([
        'email' => Input::get('email'),
        'password' => Input::get('password')
    ])) {
        return Redirect::to(Session::get('previous_url'));
    } else {
        return back();
    }
}

This way you can also set previous url and redirect back using session. I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]