You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8内置Auth模块AJAX登录后重定向未定义路由问题

Laravel 8 AJAX Phone Login Redirects to /undefined When User Exists

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:29:29