2

I'm new to Laravel 5.1, I don't know what I'm doing wrong when I'm retrieving a date string from the database and trying to show it on blade form.

It doesn't work, the date from de database does not appear on the Form::date.

I know I'm missing something crucial here :)

Here is the view code:

<div class="col-sm-6">
    <div class="form-group">
        {!! Form::label('birth_date', trans('userapps/userapps.birth_date'))!!}
        {!! Form::date('birth_date', Input::old('birth_date'), array('class' => 'form-control input-lg'))!!}
        @if ($errors->has('birth_date')) <p class="help-block">{{ $errors->first('birth_date') }}</p> @endif
    </div>
</div>

Here is the controller code:

public function edit($id)
{
    //show all saved values for editing

    $userapp = UserApplication::findOrFail($id);

    $birth_date = DateTime::createFromFormat('d/m/Y', $userapp->birth_date)->format('d/m/Y');


    $data = array('birth_date' => $birth_date, 'userapp' => $userapp);

    return view('admin/userapps/edit')->with($data);
}

Thanks in advance.

Bogdan
  • 43,166
  • 12
  • 128
  • 129
Bruno
  • 1,032
  • 1
  • 16
  • 40

1 Answers1

2

The date input only accepts values in the following format yyyy-dd-mm. Meaning you should format your date value like this:

DateTime::createFromFormat('d/m/Y', $userapp->birth_date)->format('Y-m-d');

The browser will make sure to show it according the operating system locale. For example, if I have a date input with value="2015-12-05", it will be displayed as 05/12/2015 according to my OS locale.


Once you have that fixed there is another problem which will most likely prevent the date from being displayed. You're setting the default value to Input::old('birth_date'), which is null the first time you access the form, because there's no old input data until the form has been submitted. So in your controller action you should do this:

public function edit($id)
{
    $userapp = UserApplication::findOrFail($id);

    // Use old input value and if that's not available then use the $userapp one
    $birth_date = Input::old('birth_date') ?: DateTime::createFromFormat('d/m/Y', $userapp->birth_date)->format('Y-m-d');
    $data =['birth_date' => $birth_date, 'userapp' => $userapp];

    return view('admin/userapps/edit')->with($data);
}

And in your Blade view file:

{!! Form::date('birth_date', $birth_date, array('class' => 'form-control input-lg'))!!}

With this it will use the old input value only if there is one, otherwise it will use the value from the database.


That being said, your should be aware that the date input is supported only by a few browsers. Firefox, Safari and Internet explorer don't support it at all, so if you need to make sure the user input is restricted to a date across all browsers, I would use a JavaScript date picker library instead.

Community
  • 1
  • 1
Bogdan
  • 43,166
  • 12
  • 128
  • 129