为什么碳不会在循环中发挥作用?

时间:2017-08-01 12:30:41

标签: php laravel

这是我的代码:

foreach($tasks as &$task){
    dd(Carbon::parse($task->created_at)->diffForHumans());
}

打印"2 hours ago"。一切都很好。

现在当我删除dd()时,它会抛出错误:

foreach($tasks as &$task){
    $task->created_at = Carbon::parse($task->created_at)->diffForHumans();
}

/*It throws:
    (1/1) InvalidArgumentException
     A two digit month could not be found
     Data missing

有人怎么解决?

2 个答案:

答案 0 :(得分:1)

要知道created_at是Carbon的一个实例,所以不需要解析,如果你想要,也可以直接从视图中执行此操作

{{$task->created_at->diffForHumans()}}

它失败了,因为当你2 hours ago$task->created_at = Carbon::parse($task->created_at)->diffForHumans();字段中放置一个Carbon实例时,Laravel想要解析created_at

答案 1 :(得分:-2)

  

dd函数转储给定的变量并结束执行   脚本

所以第一次迭代成功,其中一次调用失败。

  

如果您不想暂停脚本的执行,请使用转储   而不是功能

更简单的例子,因为它似乎无法理解我的意思:

$example_array = [1, 2, null];
foreach($example_array as &$element){
    $var = Carbon::parse($element); // will fail because of the null value in the array
}
 $example_array = [1, 2, null];
    foreach($example_array as &$element){
        dd(Carbon::parse($element)); // will work because it will stop executing after the first element which is not null
    }