Fil
Fil

Reputation: 8873

Trying to render the date

I have this code,

<div class="form-group">
  <label class="col-sm-2 control-label" for="date-created">Date Created</label>
  <div class="col-sm-10">
    @if (isset($post->created_at))
      <input type="date" class="form-control" id="date-created" name="created_at" value="{{ date('d/m/Y', strtotime($post->created_at)) }}">
    @else
      <input type="date" class="form-control" id="date-created" name="created_at" placeholder="Enter the date the blog post created">
    @endif
  </div>
</div>

What I am trying to do is, display the date back from the database to the input box of type allowing user to edit the date.

but this was shown when rendering on the browser

enter image description here

What the best thing to do with that?

This may be a simple problem, but I don't find a simple explanation for why it doesn't work for me.

Upvotes: 0

Views: 260

Answers (2)

Namoshek
Namoshek

Reputation: 6544

The only thing you are doing wrong is the date format, which is YYYY-MM-DD according to the Mozilla Developers Guide for the <input type="date"> field. So you only need to switch your date format string to Y-m-d.

Alternatively, you can also use the Carbon approach mentioned by AntonyMN and use the function toDateString(). If you set created_at field as part of the $date fields with protected $dates = ['created_at']; in your model, you won't even need to parse the date string into a Carbon object. The model will simply return a Carbon object on demand.

By the way, I don't think using a placeholder works on a date input field due to the fixed format of the input.

Upvotes: 2

AntonyMN
AntonyMN

Reputation: 919

Laravel comes with Carbon nesbot included out of the box to help format date. Dates in laravel can be easily formatted like this:

{{\Carbon\Carbon::parse($post->created_at)->format('d/m/Y') }}

{{\Carbon\Carbon::parse($post->created_at)->format('jS M Y') }}

Just showing some options. You can get the full documentation on date formats here

In your case, the code should be

@if (isset($post->created_at))
  <input type="date" class="form-control" id="date-created" name="created_at" value="{{ \Carbon\Carbon::parse($post->created_at)->format('d/m/Y') }}">
@else
  <input type="date" class="form-control" id="date-created" name="created_at" placeholder="Enter the date the blog post created">
@endif

Upvotes: 1

Related Questions