harryg
4 years ago
228
3
Laravel

Laravel date parsing from datetime-local and freeform date request data

Posted 4 years ago by harryg

A very handy feature of Laravel is the ability of make use of automatic date mutators. This means, say I have a published_at attribute in my model I can add this to a $dates array and Laravel will automatically parse this to a Carbon instance and vice-versa when retrieving and persisting to the database.

On one of my forms, rather than make use of a datepicker library I thought I'd try the datetime-local input type (which currently has limited support but is in the HTML spec). This uses a format like 2012-12-14T19:00. This causes a problem with Laravel's date mutator as it assumes a format, usually based on the database in use (although you can override this it seems) and uses this the parse the date before saving.

What it comes down to is that I need to add my own mutator to my model to handle irregular date formats:

public function setPublishedAtAttribute($date)
{
    if (is_string($date))
        $this->attributes['published_at'] = Carbon::parse($date);
}

This can handle unexpected date formats so should also work if the datetime-local input isn't supported and falls back to a text input into which a use types the datetime in their own format. It seems this is fired before going through to the eloquent date parser which therefore receives a Carbon instance and just passes it on.

Shouldn't Eloquent be able to handle this natively? I imagine Carbon::parse() is slower than Carbon::createFromFormat() but it should be negligible.

Please sign in or create an account to participate in this conversation.