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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题