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

Laravel 10密码验证开发报错:字段‘Password’无默认值求助

Laravel密码验证功能报错求助

我正在开发一个Laravel项目,实现密码验证功能时遇到错误,恳请Laravel专家提供帮助。相关代码及配置如下:

HTML代码

<div class="input-field">
    <label for="pw">Password</label>
    <div class="inpt">
        <input type="Password" id="pw" name="password" placeholder="Enter Password">
    </div>
</div>
<div class="input-field">
    <label for="cpw">Confirm Password</label>
    <div class="inpt">
        <input type="password" id="cpw" name="password_confirmation" placeholder="Enter Confirm Password">
    </div>
</div>

迁移文件(Migration)

$table->string('Password');
$table->string('Password_confirmation');

控制器(Controller)代码

public function store(Request $request):RedirectResponse{
   
    Registrationform::create($request->all());
    return redirect()->route('register');

    $validation = $request->validate([
        'password' => 'required|confirmed'
    ]); 
}

SQL模式

本地服务器SQL Mode设置:
NO_ZERO_IN_DATE, NO_ZERO_DATE, NO_ENGINE_SUBSTITUTION

错误信息

SQLSTATE[HY000]: General error: 1364 Field 'Password' doesn't have a default value (Connection: MySQL, SQL: insert into registration forms (First_Name, Last_Name, E_mail, ConfirmE_mail, Gender, birthday_day, birthday_month, birthday_year, UserName, updated_at, created_at) values (crafts, fsdfds, aziz1@gmail.com, aziz2@gmail.com, O, 27, 6, 2023, dafs, 2023-07-08 03:51:29, 2023-07-08 03:51:29))


问题分析及解决步骤

  1. 控制器代码顺序错误
    你先执行了入库操作再写验证代码,而且入库后直接return跳转,导致验证逻辑永远不会执行。必须先做验证,再执行入库。

  2. 字段大小写不匹配
    迁移文件里的字段是Password(首字母大写),但表单输入框的name是password(全小写),Laravel接收表单参数时键名是小写,入库时无法匹配到Password字段,因此报错该字段无默认值。建议数据库字段统一用蛇形小写命名(比如password),和表单name保持一致。

  3. 无需存储password_confirmation字段
    password_confirmation仅用于验证密码一致性,不需要存入数据库,迁移文件里要删掉这一行,只保留password字段。

修正后的代码示例

控制器代码

public function store(Request $request): RedirectResponse{
    // 先执行验证
    $validated = $request->validate([
        'password' => 'required|confirmed'
    ]); 

    // 合并其他需要入库的字段,或确保模型$fillable包含对应字段
    Registrationform::create($validated + $request->only(['First_Name', 'Last_Name', 'E_mail', 'Gender', 'birthday_day', 'birthday_month', 'birthday_year', 'UserName']));
    return redirect()->route('register');
}

迁移文件

$table->string('password'); // 改为小写,移除Password_confirmation字段

模型(Registrationform)

确保模型的$fillable包含允许批量赋值的字段,避免批量赋值错误:

protected $fillable = ['password', 'First_Name', 'Last_Name', 'E_mail', 'ConfirmE_mail', 'Gender', 'birthday_day', 'birthday_month', 'birthday_year', 'UserName'];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:27:23