In my Laravel 5.8 application, I have:
config/app.php
'date_format' => 'd/m/Y',
'date_format_js' => 'dd/mm/yy',
Model
use Carbon\Carbon;
class HrHolidayDate extends Model
{
protected $table = 'hr_holiday_dates';
protected $fillable = [
'holiday_name',
'holiday_date',
];
protected $dates = [
'holiday_date'
];
protected $casts = [];
public function setHolidayDateAttribute($input)
{
$this->attributes['holiday_date'] =
Carbon::createFromFormat(config('app.date_format'), $input)->format('Y-m-d');
}
public function getHolidayDateAttribute($input)
{
return Carbon::createFromFormat('Y-m-d', $input)
->format(config('app.date_format'));
}
}
I tried to format it in the Blae view as shown below:
view
@foreach($holidays as $key => $holiday)
<td>
{{Carbon\Carbon::parse($holiday->holiday_date)->format('d-m-Y') ?? '' }}
</td>
@endforeach
When I wanted to render the view blade, I got this error:
[2020-07-15 11:57:56] production.ERROR: DateTime::__construct(): Failed to parse time string (16/07/2020) at position 0 (1): Unexpected character (View: C:\xampp\htdocs\laravelapp\resources\views\hr\holiday_dates\index.blade.php) {"userId":466,"exception":"[object] (ErrorException(code: 0): DateTime::__construct(): Failed to parse time string (16/07/2020) at position 0 (1): Unexpected character (View: C:\xampp\htdocs\laravelapp
esources\views\hr\holiday_dates\index.blade.php) at C:\xampp\htdocs\laravelapp\vendor
esbot\carbon\src\Carbon\Traits\Creator.php:81, Exception(code: 0): DateTime::__construct(): Failed to parse time string (16/07/2020) at position 0 (1): Unexpected character at C:\xampp\htdocs\laravelapp\vendor
esbot\carbon\src\Carbon\Traits\Creator.php:81) [stacktrace]
How do I resolve it?
Thanks
Because Carbon does not understand d/m/Y
format out of the box. If you use slashes it should be mm/dd/yyyy
in that case. d/m/Y
is not an official date format.
You can use :
{{ Carbon\Carbon::createFromFormat('d/m/Y', $holiday->holiday_date)->format('d-m-Y') }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With