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

Sagaio's avatar

Modify Carbon::createFromFormat

I'm posting Y-m-d H:i to my Laravel API and I get the following:

exception 'InvalidArgumentException' with message 'Data missing' in C:\Users\Anton\Dropbox\Sites\coachlog\vendor\nesbot\carbon\src\Carbon\Carbon.php:425

Specifically in the stack trace I can see this: Carbon\Carbon::createFromFormat('Y-m-d H:i:s',...) which makes me think that I need to somehow modify Carbon or extend it so that it doesn't need the :s-part.

I've tried the following but that doesn't seem to have any effect:

    public function setNotifyAtAttribute($value){
        return $this->asDateTime($value)->format('Y-m-d H:i');
    }

I also have this:

    public function getNotifyAtAttribute($value){
        return $this->asDateTime($value)->format('Y-m-d H:i');
    }

Anyone know how to proceed here?

0 likes
5 replies
lunaticsz's avatar

Why do you remove the "s" (seconds) part? What are you trying to do here? You're not following standardized datetime format I think.

Sagaio's avatar

I'm not interested in the second. I want to create a reminders app but there is no point in having seconds entered when you chose when to be reminded. Like your phone, when you set the alarm clock you don't specify seconds, just hours and minutes. Does that make sense? I don't know if this is the way to proceed. Perhaps I should change the database column type to string?

Snapey's avatar

From the docs

By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

so you should be able to set in your model;

protected $dateFormat('Y-m-d H:i');

and then a date passed to the model will be parsed against that format.

Alternatively, if you want this to be restricted to just this one field, then use a mutator;

    public function setNotifyAtAttribute($value){
        $this->attributes['notify_at'] = Carbon::createFromFormat('Y-m-d H:i',$value);
    }

I had to guess at your fieldname. Set it appropriately.

Ixalmida's avatar

I know this thread is a year old, but does anyone know the equivalent for changing how models convert dates FROM the database? I'm connecting to an Azure database and the date format is: 'Y-m-d H:i:s.u'. Carbon seems to have a problem with the "u" (microseconds) part as it only expects 3 digits of the 6 that Azure stores. Do I have to do this with accessors on every model?

Please or to participate in this conversation.