0
votes

I'm using laravel and backpack, and I'm trying to change the format of a date field from yyyy-mm-dd to mm/dd/yyyy before I save it to the database. I know that this is not a real date format by database standards, but unfortunately I have no choice. Here is my date field:

<!-- Date-->
        @php
            $ISODate = \Carbon\Carbon::parse($entry->DATE)->format('Y-m-d');
        @endphp
       <div class="form-group col-md-12">
        <label>Date</label>
            <input
            type="date"
            name="DATE"
            id="DATE"
            value= "{{ $ISODate }}"
            class="form-control"
        >
        </div>

Here is the update function in the controller:

 public function update(UpdateRequest $request)
{
    $this->crud->hasAccessOrFail('update');

    // fallback to global request instance
    if (is_null($request)) {
        $request = \Request::instance();
    }

    // update the row in the db
    $item = $this->crud->update($request->get($this->crud->model->getKeyName()),
                        $request->except('save_action', '_token', '_method'));
    $this->data['entry'] = $this->crud->entry = $item;

    // show a success message
    \Alert::success(trans('backpack::crud.update_success'))->flash();

    // your additional operations before save here

    $item->DATE = Carbon::parse($item->DATE)->format('d/m/Y');


    $redirect_location = parent::updateCrud($request);
    // your additional operations after save here
    // use $this->data['entry'] or $this->crud->entry
    return $redirect_location;
}

This correctly parses the input date from mm/dd/YYYY to YYYY-mm-dd required for the browser's datepicker. This code also updates the column in the database, but it is still in the ISO format. It does not produce any errors.

What is the best way to convert the date format before saving the row or updating immediately after saving, etc.

Thank you

2
You should try to save the date in standard format and format it your need when you present the date in your views - chanafdo

2 Answers

0
votes

You can use carbon to format the date

echo \Carbon\carbon::createFromFormat('d/m/Y',$inputdata)->format('Y-m-d');

This will take the $inputdata in the form of mm/dd/YYYY and will convert the same to YYYY-mm-dd. Lemme know if this works

0
votes

No, that did not work. I was able to figure it out, here is what worked for me:

   $this->crud->entry->update(['DATE' => Carbon::parse($request->DATE)->format('m/d/Y')]);