5

At the moment, I have a date field on a form that I would like to be able to insert the current value of the current record being edited. No records are missing this date field in my MySQL database, but for some reason, the value of the record will not actually load into the field input, it does however load into the "value" portion of the input field.

At the moment here is my field's code:

<input type="date" name="date" id="date" class="form-control" style="width: 100%; display: inline;" onchange="invoicedue(event);" required value="{{$shipment->date}}">

And here is the code output:

<input name="date" id="date" class="form-control" style="width: 100%; display: inline;" onchange="invoicedue(event);" required="" value="2018-05-10 00:00:00" type="date">

But this is what it looks like in my browser:

enter image description here

But in my MySQL database table, the field (which is a date field) is formatted as following: 2018-05-12

3 Answers 3

16

When using <input type="date">, the value will need to be formatted in ISO 8601 date format: YYYY-MM-DD

Try mutating your $shipment->date value by appending ->format('Y-m-d') and it should match the expected format.

Give this a shot:

    <input 
        ...
        value="{{ $shipment->date->format('Y-m-d') }}" 
        ...
    >

You can learn a bit more about it here:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date https://en.wikipedia.org/wiki/ISO_8601

3

For dates you can use mutators in laravel check Documentations

Then you can do something like this:

class Shipment extends Model {

    protected $dates = ['date'];
}

Then you can simply write

<input type="date" name="date" id="date" class="form-control" style="width: 100%; display: inline;" onchange="invoicedue(event);" required value="{{$shipment->date->format('m/d/Y')}}">

If you don't want to use laravels date mutator, you can use your own something like this:

class Shipment extends Model
{
    /**
     * Set the date attribute.
     *
     * @param  string  $value
     * @return void
     */
    public function setDateAttribute($value)
    {
        $this->attributes['date'] = Carbon::parse($value)->format('m/d/Y');
    }
}

Hope this helps.

1

Laravel makes use of carbon and makes tasks like this an absolute walk in the park. Post your date value to your controller like normal, the input you're using is fine.

Then simply format with Carbon

$formattedDate = Carbon::parse($request->date)->format('Y-m-s');

You now have yourself a date in the format 2018-05-13 which is the correct format for sql

You should take a read of the Carbon documentation it can do some great things.

Check it out here https://carbon.nesbot.com/docs/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.