首页 > 解决方案 > 迁移中的默认值 0 忽略请求值 laravel

问题描述

我有桌子(产品)

Products 表有三列( id 、 product_name 、 product_quantity )

如果输入为空,我希望 product_quantity 列默认设置值为 0

这是迁移代码:

 public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();

        $table->string('product_name');
        $table->integer('product_quantity')->default('0');
        
        $table->timestamps();
    });
}

这是 ProductsController 代码:

 public function store(Request $request)
{
    
    $rules = [
        'product_name' => 'required',
       //  'product_quantity' => 'nullable',
    ];

    $customMessages = [
        
        'product_name.required' => 'please insert product name ',
      
    ];

    Product::create($this->validate($request, $rules, $customMessages));

    return back();
}

和这个产品型号代码:

Protected $fillable = ['product_name' ,'product_quantity'];

但是当我存储具有任何值的请求时,它会忽略该值并保存默认值(0)

标签: laravelvalidationmigration

解决方案


首先,您必须注意在迁移default()方法中设置的值。如果您使用的是integer类型,则传入 a 是不正确stringdefault()

$table->integer('product_quantity')->default(0); // turn the '0' into 0

另一个观察是$this->validate()方法只返回一个经过验证的数据数组,所以如果你已经评论了验证规则 product_quantity,它永远不会被传递给Product::create()。话虽如此,数据库没有收到product_quantity价值,所以它设置为默认值(0)。

如果您想product_quantity被传递给Product::create()您必须取消注释该值的规则。

我希望这个解释对你有所帮助。


推荐阅读