Laravel 日期为空字符串时缺少碳数据

Laravel Carbon data missing when date is an empty string

在我的模型中,我有以下内容:

protected $dates = ['start_date'];

我正在使用 'date' 类型的输入字段来 select 日期。如果用户删除日期,它的值将变为空字符串“”。 更新我的模型时,出现以下错误:

exception: "InvalidArgumentException"
file: "C:\www\projects\crm\vendor\nesbot\carbon\src\Carbon\Carbon.php"
line: 582
message: "Data missing"

我可以通过使用像这样的修改器来避免这个错误:

public function setStartDateAttribute($value)
{
    if ($value) {
        $this->attributes['start_date'] = $value;
    } else {
        $this->attributes['start_date'] = null;
    }
}

问题: 有没有 faster/better 方法比使用修改器处理将空字符串存储为日期更有效?

深入研究一下:

5.4 中更新的中间件

Laravel 5.4 在默认中间件堆栈中包含两个新中间件:TrimStringsConvertEmptyStringsToNull

These middleware will automatically trim request input values and convert any empty strings to null. This helps you normalize the input for every request entering into your application and not have to worry about continually calling the trim function in every route and controller.

发件人:https://laravel.com/docs/5.4/releases#laravel-5.4

所以,当我抓取请求对象时,一个空的日期字段被转换为 null。数据库允许这些字段为空,一切正常。

因此,通过前端,可以无误地输入和删除日期字段。根据您的要求手动更新为空字符串时

\App\Yourmodel::find(7)->update(["your_date_field" => ""]);  

我有同样的 data missing 错误。

问题是,您是否特别需要传递一个空字符串,或者让字段可为空是一个更好的选择?

\App\Yourmodel::find(7)->update(["your_date_field" => null]);