Carbon\Carbon::now() throws InvalidArgumentException with message 'Trailing data'

Rich Jenks picture Rich Jenks · Apr 5, 2015 · Viewed 20.4k times · Source

When running the following in Laravel Artisan Tinker:

$article = new App\Article;
$article->published_at = Carbon\Carbon::now();

I get this error:

InvalidArgumentException with message 'Trailing data'

However, Carbon\Carbon::now() on it's own returns a Carbon instance as expected.

published_at should be mutated into Carbon instance via protected $dates = ['published_at']; in the model and it's also included in protected $fillable.

Anyone know what's going on here or how I can resolve?


EDIT: Same thing happens when ran in a closure in routes, so not specific to Tinker

EDIT 2: Looks like others are experiencing this: https://laracasts.com/discuss/channels/general-discussion/carboncarbonnow-giving-error and twice in comments for https://laracasts.com/series/laravel-5-fundamentals/episodes/8

EDIT 3: Pretty much exactly the same code as the first example is used in https://laracasts.com/series/laravel-5-fundamentals/episodes/15 at 15:10 without error.

EDIT 4: Swapping line 2 of the above code to $article->published_at = Carbon::now()->format('Y-m-d'); works fine and even includes time when stored in the database (although not sure why).

I'd guess that "trailing data" could refer to the full datetime being too long, but seems strange that Laravel does so much with datetimes automatically (auto-converting to Carbon instances, for example) but not this.

Usage in Edit 3 would be preferable though!

Answer

Alexander Kleinhans picture Alexander Kleinhans · Aug 17, 2015

I've found that you should should not use createFromFormat, unless the second paramater $date is also a Carbon object, but if it's not and it's just a string you can just use

public function setPublishedAtAttribute($date){
    $this->attributes['published_at'] = Carbon::parse($date);
}

I think there's a little more overhead with regards to it having to figure out what format it's in, but this was my temporary workaround.

'Y-m-d' is the way the front parsed it into the form, but it's going into a database which is what Carbon spits out. I got the same error:

[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

I believe in the first part of the stack trace,

Carbon\Carbon::createFromFormat('Y-m-d', Object(Carbon\Carbon))

indicates that the second parameter must be a Carbon object, so you may have to make sure that is the case on the form rather than just date('Y-m-d') as you would in PHP.