Laravel 在空字段中更新或插入值

问题描述

我在空字段中插入值时遇到问题。

这是桌子

public function up()
    {
        Schema::create('users',function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('username')->unique()->nullable();
            $table->string('mobile_no')->nullable();
            $table->string('address')->nullable();
            $table->string('email')->unique();
            $table->boolean('role_name')->default(0);
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

这是用户控制器

public function update(Request $request,User $user)
    {
        $request->validate([
            'name' => 'required|max:255','mobile_no' => 'required|max:11','address' => 'required|max:255',]);
        $user->update($request->all());
        return redirect()->route('profile')->with('updated','Profile successfully updated');
    }

我没有收到错误消息,$message 总是说:“配置文件已成功更新”,但它并没有真正更新。

解决方法

您是否在模型中声明该字段可填写?

    protected $fillable = [
    'name','username',.....
];

https://laravel.com/docs/8.x/eloquent#inserting-and-updating-models