在 Laravel Artisan Tinker 中运行以下命令时:
$article = new App\Article;
$article->published_at = Carbon\Carbon::now();
我收到此错误:
InvalidArgumentException with message 'Trailing data'
然而,
Carbon\Carbon::now()
自行返回 Carbon
实例如预期。published_at
应该通过 protected $dates = ['published_at'];
变异为 Carbon 实例在模型中,它也包含在 protected $fillable
中.任何人都知道这里发生了什么或我该如何解决?
编辑:在 route 的闭包中运行时会发生同样的事情,因此并非特定于 Tinker
编辑 2:看起来其他人正在经历这个:https://laracasts.com/discuss/channels/general-discussion/carboncarbonnow-giving-error和两次评论 https://laracasts.com/series/laravel-5-fundamentals/episodes/8
编辑 3:与 https://laracasts.com/series/laravel-5-fundamentals/episodes/15 中使用的第一个示例几乎完全相同的代码在 15:10 没有错误。
编辑 4:将上述代码的第 2 行交换为
$article->published_at = Carbon::now()->format('Y-m-d');
工作正常,甚至包括存储在数据库中的时间(虽然不确定为什么)。我猜想“尾随数据”可能是指完整的日期时间太长,但 Laravel 自动对日期时间做了这么多事情(例如,自动转换为 Carbon 实例)而不是这个,这似乎很奇怪。
不过,在 Edit 3 中使用会更可取!
最佳答案
我发现你不应该使用 createFromFormat
, 除非第二个参数 $date
也是一个 Carbon 对象,但如果不是并且它只是一个字符串,您可以使用
public function setPublishedAtAttribute($date){
$this->attributes['published_at'] = Carbon::parse($date);
}
我认为必须弄清楚它的格式需要更多的开销,但这是我的临时解决方法。
'Y-m-d' 是前端将其解析为表单的方式,但它会进入一个数据库,这是 Carbon 吐出的内容。我得到了同样的错误:
[2015-08-16 21:35:57] production.ERROR: exception 'InvalidArgumentException' with message 'Trailing data' in /Users/alexanderkleinhans/laravel/vendor/nesbot/carbon/src/Carbon/Carbon .php:414
我相信堆栈跟踪的第一部分,
Carbon\Carbon::createFromFormat('Y-m-d', Object(Carbon\Carbon))
表示第二个参数必须是一个 Carbon 对象,因此您可能必须确保表单上是这种情况,而不仅仅是
date('Y-m-d')
就像在 PHP 中一样。
关于laravel - Carbon\Carbon::now() 抛出 InvalidArgumentException 和消息 'Trailing data',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29460292/