Working with DateTime field in Laravel
As is pretty common in something like a blog setting, I recently needed a published_at field for a project I was working on. I knew that in html you could have a date field, but that didn't account for time. And I needed to have time too.
Initially I thought about splitting it into two fields, one for the date, one for the time. But then that seemed to cause problems when persisting to the database.
Then I found the datetime field, which looked great except forced 24hr time, which most people "hate" using. Then I saw the datetime-local field. Great! Does exactly what I need in the most common browsers.
Set it up in an HTML form, I am using the Laravel Collective's Form package. Looks like it is right in terms of inputting data. Tested it, saved it, went to the edit screen....no data.
hmmm.
After searching and searching, testing and testing...nothing was working. I figured it had to be a format issue for the field type since I could switch the field to a text field and see the data prepopulated.
Then I tried this:
{!! Form::input('datetime-local', 'published_at', $article->published_at->format('Y-m-d\TH:i'), ['class' => 'form-control']) !!}
Formatting the date in this format, allows the field to be populated with existing data. The \
just escapes the T.