【发布时间】:2017-10-14 11:59:32
【问题描述】:
在我的模型中,我有以下内容:
protected $dates = ['start_date'];
我正在使用“日期”类型的输入字段来选择日期。如果用户删除日期,其值将变为空字符串“”。 更新我的模型时,我收到以下错误:
exception: "InvalidArgumentException"
file: "C:\www\projects\crm\vendor\nesbot\carbon\src\Carbon\Carbon.php"
line: 582
message: "Data missing"
我可以通过使用这样的 mutator 来避免这个错误:
public function setStartDateAttribute($value)
{
if ($value) {
$this->attributes['start_date'] = $value;
} else {
$this->attributes['start_date'] = null;
}
}
问题: 有没有比使用 mutator 更快/更好的方法来处理将空字符串存储为日期?
【问题讨论】:
-
你在某处使用
Carbon::createFromFormat($format, $time, $tz);吗? -
我没有明确使用它,但是 Laravel 在将字段设置为日期时会使用它(laravel.com/docs/5.5/eloquent-mutators#date-mutators)。
-
我以前没有遇到过。在一个应用程序中,我有许多日期字段。它们在迁移中被标记为可为空,并列在模型的日期数组中。这一切都可以正常工作,无需修改器。
-
你可以试试
\App\Yourmodel::find(7)->update(["your_date_field" => ""]);吗?
标签: php laravel php-carbon