Laravel 8内置Auth模块AJAX登录后重定向未定义路由问题
Let's break down your issue and fix it step by step:
Problem Analysis
The core issue here is a missing url property in your successful login response, paired with unconditionally trying to redirect using response.url in your AJAX callback.
When a user exists and logs in successfully, your controller only returns status and message in the JSON response—no url field. Since your AJAX code runs window.location = response.url regardless of the login status, response.url becomes undefined, leading the browser to attempt redirecting to /undefined.
Conversely, when the user doesn't exist, your controller correctly includes url: route('register') in the response, so the redirect works as expected.
Fix Steps
1. Update Controller to Include Redirect URL on Successful Login
Modify the successful login response in your controller to add the url property pointing to your authenticated dashboard route:
public function login(Request $request) { // Check validation $this->validate($request, [ 'mobile' => 'required|regex:/[0-9]{10}/', ]); // Get user record $user = User::where('mobile', $request->mobile)->first(); if($user){ // This check is redundant since we fetched the user by mobile, you can remove it // if($request->mobile != $user->mobile) { ... } // Set Auth Details Auth::login($user); // Add the url property for successful redirect return response()->json( [ 'status' => true, 'message' => 'Login Successfully', 'url' => route('dashboard') // Point to your authenticated home route ], Response::HTTP_OK ); }else{ Cookie::queue('otpVerified', true); Session::put('mobile',$request->mobile); return response()->json( [ 'status' => false, 'message' => 'User Not Exist', 'url' => route('register') ], Response::HTTP_OK ); } }
2. Refine AJAX Callback Logic
Adjust your AJAX success handler to handle redirects clearly based on the login status (though now we'll ensure url exists in all responses):
$.ajax({ type: "POST", url: "/login", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, data: { 'mobile' : user.phoneNumber }, success: function (response){ if (response.status === true){ console.log('Login successful!'); // Redirect to dashboard for successful login window.location = response.url; } else { // Redirect to register if user doesn't exist window.location = response.url; } }, error: function(xhr) { // Optional: Handle validation errors or server issues here console.error('Login failed:', xhr.responseText); } });
Quick Cleanup Tip
The check if($request->mobile != $user->mobile) is redundant—since you fetched the user using User::where('mobile', $request->mobile)->first(), the mobile numbers will always match. You can remove that block to clean up your controller code.
内容的提问来源于stack exchange,提问作者Irshad Khan

