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 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化