2015-04-05 78 views
6

当运行在Laravel工匠廷克如下:碳碳::现在()抛出与消息 '尾随数据' InvalidArgumentException

$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'];突变为碳实例,它也包含在protected $fillable中。

任何人都知道这里发生了什么事或我如何解决?


编辑:同样的事情发生时,在路线封闭运行,所以不特定廷克

编辑2:两次征求意见https://laracasts.com/series/laravel-5-fundamentals/episodes/8

https://laracasts.com/discuss/channels/general-discussion/carboncarbonnow-giving-error和:看起来像其他人也遇到这种编辑3:与第一个例子几乎完全相同的代码在15:33时在https://laracasts.com/series/laravel-5-fundamentals/episodes/15中使用,没有错误。

编辑4:上面代码的第2行换到$article->published_at = Carbon::now()->format('Y-m-d');工作正常,甚至包括存储在数据库中的时间(虽然不知道为什么)。

我猜想“尾随数据”可能指的是完整的日期时间太长,但看起来很奇怪,Laravel自动对日期时间做了很多事情(例如自动转换为Carbon实例),但不是这样。

编辑3中的使用将是可取的,但!

+0

看起来像一个常规的DateTime错误,但它不应该用'now()'方法发生。你的时区设置有什么错误吗? config/app.php中的时区配置是什么样的? – kajetons 2015-04-05 18:27:12

+0

时区是默认值:''timezone'=>'UTC',' – 2015-04-05 18:31:28

+0

通过查看源代码,它看起来像它不会越过这条线返回新的DateTimeZone(date_default_timezone_get());'在课堂建设。如果这不会引导你到任何地方,我怀疑除了使用本地日期函数外你可以做任何事情。 – kajetons 2015-04-05 18:43:30

回答

-1

只是删除这个功能:

public function setPublishedAtAttribute($date){ 
    $this->attributes['published_at']=Carbon::createFromFormat('Y-m-d',$date); 
} 

监守那修为已经published_at领域的格式...

2

我发现,你应该不应该使用createFromFormat,除非第二paramater $date是也是碳的对象,但如果它不是,它只是一个字符串,你可以使用

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))

表明,第二个参数必须是一个碳对象,所以你可能要作出肯定的是这种情况在表单上,​​而不是像在PHP中那样只是date('Y-m-d')

1

我在跟着Laracast教程,我遇到了同样的错误。我终于明白这个例外有什么问题。

在功能:

public function setPublishedAtAttribute($date) 
{ 
    $this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date); 
} 

发现我的$日期格式为'YMD'

然而,在我create.blade.php和edit.blade.php,形式输入:

{!! Form::input('data-date', 'published_at', date('d-m-Y'), ['class' => 'form-control']) !!} 

注意到,我的日期格式为'DMY'

这就是Laravel抛出异常的原因。

将日期格式与所有文件中的'Y-m-d'相同后,异常消失。我希望这有帮助。

0

如果数据库是用这样的小数microtime中返回的日期值,您将收到此错误:

2016-10-06 20:16:23.96034

这些额外十进制数字都是问题。删除这些,它应该工作。