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

lcjury's avatar

How to use Carbon in models without time (hours and seconds), just the date

I'm using the following

protected $dates = ['date']; 
protected $dateFormat = 'm/d/Y';

. So, what I expect is when I do: $model->date = "10/16/1991" it stores that date inside Carbon (And that is what happens), the problem is, when I do {{$model->date}} on a view, it prints: 1991-10-16 01:06:14.

What I try until now?, I try to change the function getDateAttribute, but I do want to return a Carbon instance instead of just a string.

So, what could solve my problem is if I could tell carbon that, when the carbon instance is printed it use an especific format.

Why? I want to avoid using {{$model->date->format('m/d/Y')}} in the view and just use {{$model->date}} but with the latter returning a carbon instance.

0 likes
4 replies
crazytoon's avatar

Have you tried?: protected $dates = ['field_name'];

Obviously change the field_name with your field name. Add it to the model you want to use it with.

(I am not sure I understood your question correctly tho.. so just clarify if this is not what you wanted)

lcjury's avatar

Forgot to say that I'm using protected $dates with protected $dateFormat. (Main post edited)

Snapey's avatar

You can use the setToStringFormat command to change the default format, but I'm not sure if this is global or can be used against a specific carbon instance. see http://carbon.nesbot.com/docs/#api-formatting

You might be able to use a mutator, set the default string format and then return the carbon object ?

lcjury's avatar
lcjury
OP
Best Answer
Level 2

Ok, so, my problem really was that I was trying to use the date format 'd/m/Y' when the date type of mysql stores it in another format. So, I missunderstood$dateFormat. My solution is:

protected $dates = ['birthday'];

public function setBirthdayAttribute($birthday){ 
return $this->attributes['birthday'] = \Carbon\Carbon::createFromFormat('d/m/Y', $birthday);
}
public function getBirthdayAttribute($birthday){
return $this->asDateTime($birthday)->format('d/m/Y'); 
}

So, I was expecting for $dateFormat to do all that boilerplate code, I don't know why there isn't any property that let me do this without having explicitly write the getters & setters.

Please or to participate in this conversation.