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:
- Modify the purchase button link to include a
nextparameter 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
- In your
LoginController, override theauthenticatedmethod to redirect the user to the intended URL if thenextparameter 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');
}
- Ensure that your middleware is set up to use the intended URL. Laravel's
Authenticatemiddleware 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.