ethar's avatar
Level 5

redirect to specific page after login

I work on website like Udemy. when the student clicks on the purchase button if the user logged in must go to the payment page. if not must go to the login page, and then redirect to the payment page, and this page must show the selected course. in web.php i use this middleware for route

Route::controller(PurchaseController::class)->group(function () {
    Route::group(['middleware' => ['auth:students']], function () {
        Route::get('/purchase/{id}/{slug?}', 'purchase')->name('student.purchase');
    });
});

my question if user not logged in, and login successfully, how redirect to payment page and show the selected item.

in udemy i see this url

https://www.udemy.com/join/login-popup/?next=%2Fpayment%2Fcheckout%2Fexpress%2Fcourse%2F567828%2F%3FdiscountCode%3DQ1CP24

but in my case its reditect to

http://website.test/ar/login
0 likes
1 reply
LaryAI's avatar
Level 58

To achieve the desired behavior, you can use Laravel's built-in functionality to redirect users after login to a specific URL that was intended before they were asked to log in. You can append a next query parameter to your login URL that specifies where the user should be redirected after a successful login.

Here's how you can modify your code to include this functionality:

  1. Modify the purchase button link to include a next parameter if the user is not logged in:
@if(auth('students')->check())
    <a href="{{ route('student.purchase', ['id' => $course->id, 'slug' => $course->slug]) }}">Purchase</a>
@else
    <a href="{{ route('login') }}?next={{ urlencode(route('student.purchase', ['id' => $course->id, 'slug' => $course->slug])) }}">Purchase</a>
@endif
  1. In your LoginController, override the authenticated method to redirect the user to the intended URL if the next parameter is present:
protected function authenticated(Request $request, $user)
{
    if ($request->has('next')) {
        return redirect($request->next);
    }

    // Default redirect if 'next' parameter is not set
    return redirect('/home');
}
  1. Ensure that your middleware is set up to use the intended URL. Laravel's Authenticate middleware should automatically use the intended URL if it's available in the session. If it's not working as expected, you may need to customize the middleware or check your session configuration.

By following these steps, when a user clicks on the purchase button and they are not logged in, they will be redirected to the login page with a next parameter in the URL. After they log in, the authenticated method in the LoginController will check for this parameter and redirect the user to the payment page for the selected course.

Remember to validate and sanitize the next parameter to prevent open redirect vulnerabilities. Only allow redirection to internal URLs that you expect.

Please or to participate in this conversation.