Yeah you are overwriting the cast. Just do this
public function getJobsDoneDateAttribute($value)
{
return is_null($value) ? 'Not completed' : \Carbon\Carbon::parse($value)->format('d/m/Y');
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello, I have a model with a few date fields in it.
I have this in the model:
protected $dates = ['request_date', 'jobs_done_date', 'sent_for_invoice_date'];
protected $casts = [
'request_date' => 'date:D d/m/Y',
];
I added the request_date in the $casts because I need to get it with this code:
{{ Arr::get($model->toArray(), $col->attribute) }}
And if I don't do that, the date is displayed like this:
2021-12-11T00:00:00.000000Z
Now, I have a view where I need to display the 'jobs_done_date'. If I do this:
$job->jobs_done_date->format('d/m/Y')
I get an error when the date is null.
So I tried this function in the model:
public function getJobsDoneDateAttribute($value)
{
return is_null($value) ? 'Not completed' : $value->format('d/m/Y');
}
That works fine when the date is null, but when it's not, I get this error:
Call to a member function format() on string
How do I solve this?
@SigalZ it seems to suffer the same problem with casting. You can use another name
public function getJobsDoneDateFormattedAttribute()
{
return optional($this->jobs_done_date)->format('d/m/Y') ?? 'Not completed';
}
//usage
{{$job->jobs_done_date_formatted}}
Please or to participate in this conversation.