即使在迁移中设置了默认值,批量分配也无法处理Null输入.对此有什么解决方案? [英] Mass assignment won't handle Null input even when default is set on migration.Any solution to this?

查看:32
本文介绍了即使在迁移中设置了默认值,批量分配也无法处理Null输入.对此有什么解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在大量使用任务分配.最近,我遇到了这个问题,我在其中创建了fillable,并且还默认使用null值,但是在使用批量分配时,如果我的输入为空,则会返回"Cannot Be Null"错误.

I have been using mass assignment a lot. I recently came across this issue, where I create fillable, and also defaults for null values, but on using mass assignment, if my inputs are empty, it returns a "Cannot Be Null" Error.

我的模特

protected $fillable = ['name','status'];

我的控制器

$this->model->create($request->all());

我的迁移

$table->boolean('status')->default(0);

以上所述是否意味着当我在输入字段 status 上不提供任何内容时,它应该默认为0吗?但是列不能为 null 引发.

Shouldn't the above mean that when I provide nothing on the input field status, it should default to 0? But column can't be null is thrown.

对此有什么解决办法吗?

Is there any solution to this?

推荐答案

我猜您有问题,因为 ConvertEmptyStringsToNull 中间件已添加到laravel> = 5.4中.该中间件将所有空字符串转换为 null .因此,如果您未在 status 字段中设置任何值,则它将为 null .您的迁移不是-> nullable(),因此会引发错误 Cannot Be Null .

I guess you have the problem because of ConvertEmptyStringsToNull middleware which was added to laravel >= 5.4. This middleware convert all empty strings to null. So if You don't set any value to status field it will be null. Your migration isn't ->nullable() so there is thrown error Cannot Be Null.

您可以这样解决它:

$all = $request->all();

if(is_null($request->get('status')))
{
     unset($all['status']);
}

$this->model->create($all);

这篇关于即使在迁移中设置了默认值,批量分配也无法处理Null输入.对此有什么解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆