doucuodan0897 2017-10-14 11:59
浏览 166
已采纳

当日期为空字符串时,Laravel Carbon数据丢失

In my model I have the following:

protected $dates = ['start_date'];

I am using an input field of type 'date' to select the date. If the user removes the date, its value becomes a null string "". when updating my model, I get the following error:

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

I can avoid this error by using a mutator like this:

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

Question: Is there a faster/better way than using a mutator to deal with storing an empty string as a date?

  • 写回答

1条回答 默认 最新

  • douyu7879 2017-10-15 00:09
    关注

    Looking into this a bit deeper:

    Middleware updated in 5.4

    Laravel 5.4 included two new middleware in the default middleware stack: TrimStrings and ConvertEmptyStringsToNull.

    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.

    From: https://laravel.com/docs/5.4/releases#laravel-5.4

    So, when I am grabbing the request object, an empty date field is converted to null. The database allows null on these fields and everything works correctly.

    So, through the front end, date fields can be entered and removed without error. When updating manually to an empty string as per your request

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

    I had the same data missing error.

    Question is, do you specifically need to pass an empty string or is making the field nullable a better option for you?

    \App\Yourmodel::find(7)->update(["your_date_field" => null]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?