A tutorial to show the date of a model in an HTML input of type datetime-local in a Laravel 10 project.

The French version of this publication : Laravel : Afficher une date dans un input datetime-local

An HTML input whose type attribute is datetime-local is used to present a form field to display and enter a date and time:

<input type="datetime-local" >

In this tutorial we want to see how to display a date (day, month, year, hour, minute and second) from a Laravel model in a datetime-local HTML input. At the time of writing this post, I am using Laravel version 10.3.3.

To show the date (email_verified_at, created_at, updated_at, ...) of a Laravel model in a datetime-local HTML form field, we first need to make sure that the column in the database table is defined with the timestamp data type.

In a Laravel migration, we use the timestamp() method to define the schema of a timestamp column:

$table->timestamp('email_verified_at')->nullable(); // column email_verified_at
$table->timestamps(); // columns created_at and updated_at

If you have another column that stores the date, you can convert its attribute to date format (Carbon instance) through the $casts property in the model:

protected $casts = [ "online_at" => "datetime" ];

In a view (Blade template), we can use the format() method to format the date and time into a string compatible and usable with the datetime-local HTML field to display it.

For example, for the User model with the created_at column, we can use the following syntax to display the date and time in a datetime-local field:

<input type="datetime-local" name="created_at" value="{{ $user->created_at->format('Y-m-d\TH:i:s') }}">

In this example, we use the format() method to convert the model's created_at date to a string in Y-m-d\TH:i:s format, which is the compatible format for the HTML datetime-local field. The \T character is used to separate the date and time in the string.

To display the date in an HTML input of type date, the compatible format is Y-m-d :

<input type="date" name="online_at" value="{{ $post->online_at->format('Y-m-d') }}" >

The date and time formats used in HTML are presented in this article.

Tip: Instead of formatting the date in the Blade view, we can also format it in the model via the $casts property:

 protected $casts = [ "online_at" => "datetime:Y-m-d\TH:i:s" ];

Be well 😎