Home >Backend Development >PHP Tutorial >How to Redirect Users to Their Original Destination After Laravel Login?

How to Redirect Users to Their Original Destination After Laravel Login?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 17:37:11349browse

How to Redirect Users to Their Original Destination After Laravel Login?

Laravel: Redirect User to Original Destination After Login

In Laravel, when a user attempts to access a protected route, they are redirected to the login page. After logging in, the user should be redirected back to the page they were trying to access originally.

Solution

For Laravel 5.3 and Above

  • Use the intended method in the login action to redirect the user back to the intended page. Example:
// Login action
public function login(Request $request)
{
    if (Auth::attempt($request->all())) {
        return redirect()->intended('dashboard');
    }

    return redirect('login');
}

For Laravel 5 Up to 5.2

  • Modify the auth middleware to store the requested URL in a session before redirecting to the login page.
  • In the login action, use the intended method to redirect the user back to the intended page, or a default page if there is none. Example:
// Auth middleware
public function handle($request, Closure $next)
{
    if (Auth::guest()) {
        Session::put('intended_url', request()->url());
        return redirect('login');
    }

    return $next($request);
}

// Login action
public function login(Request $request)
{
    if (Auth::attempt($request->all())) {
        return redirect()->intended('dashboard');
    }

    return redirect('login');
}

For Laravel 4

  • Use the Redirect::guest method in the auth filter to redirect the user to the login page and store the requested URL in a session.
  • In the login action, use the Redirect::intended method to redirect the user back to the intended page, or a default page if there is none. Example:
// Auth filter
Route::filter('auth', function($route, $request) {
    if (Auth::guest())
    {
        Session::put('intended_url', request()->url());
        return Redirect::guest('login');
    }
});

// Login action
public function login(Request $request)
{
    if (Auth::attempt($request->all())) {
        return Redirect::intended('dashboard');
    }

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

The above is the detailed content of How to Redirect Users to Their Original Destination After Laravel Login?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn