A textual month could not be found ,Trailing data Carbon - laravel

与世无争的帅哥 提交于 2019-12-23 22:27:01

问题


I did try different ways, but I have not get the proper time format.

$news->created_at = Carbon::parse($news->created_at)->format('M, d, Y');

$news->created_at = date('d M Y',strtotime($news->created_at))

$news->created_at = date('d M Y',$news->created_at)

$news->created_at = Carbon::createFromFormat("d M Y",strtotime($news->created_at));

$news->created_at = $news->created_at->format('M, d, Y');

And the errors are,

Unexpected data found
The separation symbol could not be found
InvalidArgumentException

Carbon.php: 910

dd($news->created_at);

Carbon @1550035143 {#361 ▼
  date: 2019-02-13 05:19:03.0 UTC (+00:00)
}

回答1:


You already have a Carbon instance in your $news->created_at field, because Eloquent models consider the created_at and updated_at columns as timestamps by default and automatically convert them to Carbon instances. So you just need to use the format method from Carbon:

$news->created_at->format('d M Y');

However, when you try to reassign a string as the value of created_at on the model instance, it conflicts with Laravel's internal mutator that tries to convert any value assigned to a date field from a Carbon instance into a string.

You could set public $timestamps = false; in your News model and then use strings throughout your app when handling model timestamps, but that seems like a hack more than a solution, because you'd be giving up on all the benefits that Carbon offers.

You also could also do this by handling timestamps at serialization time, something like this:

return collect($news->makeHidden(['created_at']))->merge([
    'created_at' => $news->created_at->format('d M Y')
]);

The above code will hide the columns passed to makeHidden from the serialization process. Then you could merge the formatted values for the hidden columns into your response.



来源:https://stackoverflow.com/questions/54690089/a-textual-month-could-not-be-found-trailing-data-carbon-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!