【问题标题】:default value 0 in migration ignore request value laravel迁移中的默认值 0 忽略请求值 laravel
【发布时间】:2020-11-09 21:11:40
【问题描述】:

我有表(产品)

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)

【问题讨论】:

  • product_quantity 在模型上设置为“可填充”吗?
  • 是的,我在模型上将 product_quantity 设置为“可填充”

标签: laravel validation migration


【解决方案1】:

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

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

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

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

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

【讨论】:

  • 当我取消注释 product_quantity 的验证规则时,出现错误 Column 'product_quantity' cannot be null ,当我将输入留空时出现此错误
  • 是的,那是因为您正在验证 product_quantity 可以为 null,所以现在它在值为 null 时由 $this->validate() 方法返回并传递给 create() 方法,所以当它必须是整数时,laravel 试图插入一个空值
  • 不要在请求中发送 product_quantity 键并将规则从 nullable 更改为 numeric,这样您将强制 product_quantity 在存在时为整数,而不是在它存在时处理它不存在,因此将设置默认值
猜你喜欢
  • 2016-10-06
  • 1970-01-01
  • 2018-11-23
  • 2016-08-28
  • 2021-12-10
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
相关资源
最近更新 更多