Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

How to format a date on a pivot table ?

Hello,

It's easy to format a date by appending a specific attribute to a model.

public function getDateFormatFrAttribute()
{
	return $this->...
}

But is there any way to do this on a pivot table which doesn't have any model ?

It's possible to format the date directly in the blade view, but is there any other way to format it like we can do it in a model ?

I have searched for such solutions, but I don't have found anything.

Thanks for your answer.

Vincent

0 likes
4 replies
tykus's avatar
tykus
Best Answer
Level 104

By default, it will be a Carbon instance, so you can format wherever it is being displayed:

@foreach ($parent->children as $child)
	{{ $child->pivot->created_at->format('Y-m-d g:i') }}
@endforeach

Or, you can implement an intermediate table model and define an accessor there.

1 like
vincent15000's avatar

@tykus Thank you ... I have an error saying that my date is a string ... so by default it's not a Carbon instance.

<td>{{ $member->pivot->ask_date->format('d/m/Y') }}</td>
...
Call to a member function format() on string

Do I have to do something to force my date to be a Carbon instance in my pivot relationship ?

vincent15000's avatar

@tykus I have done like this in my blade file.

Carbon\Carbon::parse($member->pivot->ask_date)->format('d/m/Y à g \h i')
tykus's avatar

@vincent15000 I assumed you were working with the default timestamps; in your case, I would suggest adding a PivotModel class would make things simpler; especially if you need to parse the date in more than one place in your views.

Please or to participate in this conversation.