使用Laravel Request在更新方法上传递空字段 [英] Pass empty fields on the update method using Laravel Request
问题描述
我正在通过经典的提交表单获取数据,但是由于某种原因,我没有在请求中获取所有输入数据,因此只会更新接收到的数据.
I'm getting data through a classic submitted form but for some reason I don't get all the input's data in request and it only updates the received ones.
Model::find($id)->update($request->all());
这有点问题,因为我的数据库中有多个可为空的字段,有时我想传递空字段(即,当用户清除输入然后提交表单时)
This is a bit problematic because I have multiple nullable fields in my database and sometimes I want to pass empty fields (i.e when a user clear an input then submit the form)
您还知道一种将空字段传递给请求的方法吗?
Do you know a way to pass empty fields to the Request as well?
推荐答案
The thing is, Laravel transforms the ''
values to null
by default through the ConvertEmptyStringsToNull middleware. Check your Kernel:
app/Http/Kernel.php
protected $middleware = [
// ...
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
// ...
];
此中间件执行以下操作:
This middleware do the following:
protected function transform($key, $value)
{
return is_string($value) && $value === '' ? null : $value;
}
如您所见,如果给定属性的值为''
,它将被转换为null
.
As you can see, if the given attribute has a value ''
it will be transformed to null
.
因此,要避免这种情况,您可以在内核文件中注释该中间件.但请注意这一点,因为它将应用于您的整个应用程序.
So, to avoid this you could just comment that middleware in the Kernel file. But be aware of this, because this will be applied to your entire application.
这篇关于使用Laravel Request在更新方法上传递空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!