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

Laravel仅邮箱认证:移除密码后注册生成Token报错解决方案

Fixing "Token Undefined" When Generating Bearer Token on Email-Only Signup

Hey Payne, let's get this sorted out! The issue is straightforward right now—your signup function is creating the user but not actually generating and returning the Bearer Token. You had that logic in the login function, but we need to port it over to the signup flow since you're ditching the login step entirely.

Here's how to update your signup function to generate the token immediately after creating the user:

use Carbon\Carbon;

public function signup(Request $request) {
    // Validate the incoming email
    $request->validate([
        'email' => 'required|string|email|unique:users'
    ]);

    // Create and save the new user
    $user = new User([
        'email' => $request->email
    ]);
    $user->save();

    // Generate the personal access token for the newly created user
    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;

    // Optional: Set a default expiration date (adjust timeline as needed)
    $token->expires_at = Carbon::now()->addWeeks(1);
    $token->save();

    // Return success message + token details in the response
    return response()->json([
        'message' => 'Successfully created user!',
        'access_token' => $tokenResult->accessToken,
        'token_type' => 'Bearer',
        'expires_at' => Carbon::parse($token->expires_at)->toDateTimeString()
    ], 201);
}

Key Changes Explained:

  • After saving the user, we call $user->createToken() just like you did in the login function—this generates a valid token tied directly to the new user account.
  • I kept the 1-week expiration from your original login code, but feel free to tweak this to match your app's security needs (e.g., add days instead of weeks).
  • We now include all token details in the 201 response, so the client gets the Bearer Token instantly after signup.

You can also go ahead and delete the login function entirely now—since you're skipping the login step, it's no longer needed.

The "token undefined" error you saw was because your original signup function never created or referenced a $token variable at all. This update fixes that by embedding all necessary token generation logic directly into the signup process.

内容的提问来源于stack exchange,提问作者Payne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:23:38