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

Laravel移动端无密码登录报错:未知列'password'的解决问询

Laravel移动端无密码登录解决方案

问题根源

Auth::attempt() 方法默认会检查凭证中的 password 字段,并且会尝试从数据库读取该字段进行哈希验证,这就是触发「Column not found: 1054 Unknown column 'password'」错误的核心原因。要实现仅用手机号的无密码登录,必须绕开这个默认的密码验证逻辑。

解决方案:手动处理用户查找/创建 + 直接登录

无需依赖 Auth::attempt(),通过「查找/创建用户」+ Auth::login() 方法即可完成需求,步骤如下:

1. 确保用户表与模型配置正确

如果用户表原本没有 password 字段,先添加该字段(Laravel 认证体系默认依赖此字段),可通过迁移实现:

Schema::table('users', function (Blueprint $table) {
    $table->string('password')->nullable()->default(bcrypt(Str::random(16)));
});

同时在 User 模型的 $fillable 属性中加入 mobile 和 password:

protected $fillable = ['mobile', 'password'];

2. 编写登录逻辑代码

在登录控制器中实现核心逻辑:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use App\Models\User;

public function mobileLogin(Request $request)
{
    // 验证手机号格式合法性
    $request->validate([
        'mobile' => 'required|string|regex:/^1[3-9]\d{9}$/'
    ]);

    $mobile = $request->input('mobile');

    // 查找手机号对应的用户,不存在则自动创建(填充随机加密密码)
    $user = User::firstOrCreate(
        ['mobile' => $mobile],
        ['password' => bcrypt(Str::random(16))]
    );

    // 直接登录用户,跳过密码验证流程
    Auth::login($user);

    // 返回登录成功响应
    return response()->json([
        'code' => 200,
        'message' => '登录成功',
        'data' => ['user' => $user]
    ]);
}

3. 配置对应路由

添加移动端登录的路由:

Route::post('/mobile-login', [AuthController::class, 'mobileLogin']);

方案优势

Auth::login() 方法直接接收用户实例完成登录,不会触发密码验证逻辑,完美匹配「手机号存在直接登录,不存在创建后登录」的需求。同时给新用户填充随机加密密码,既满足了 Laravel 认证体系对 password 字段的要求,又不会影响无密码登录的体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:05:08