OutForCode
OutForCode

Reputation: 451

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

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

Upvotes: 2

Views: 3767

Answers (1)

Bogdan
Bogdan

Reputation: 44526

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.

Upvotes: 1

Related Questions