Search code examples
phpformslaravellaravel-5laravel-form

Laravel 5.3 forms not retaining old input when validation fails


I have a form where users can create an item. However, when the form is submitted and does not pass validation the old inputs are not being remembered and are simply wiped which is frustrating for the user.

I am using the laravelcollective forms for this and my html looks like:

 {{ Form::open(['route' => 'my.route', 'class' => 'form-horizontal', 'files' => true]) }}

<div class="form-group">
    {{ Form::label('name', 'Name', ['class' => 'control-label col-md-3']) }}
    <div class="col-md-9">
        {{ Form::text('name', null, ['placeholder' => 'hello world' ,'class' => 'form-control']) }}
    </div>
</div>

<div class="form-group">
    {{ Form::label('description', 'Description', ['class' => 'control-label col-md-3']) }}
    <div class="col-md-9">
        {{ Form::textarea('description', null, ['placeholder' => 'hello world', 'class' => 'form-control']) }}
        <span>some sub-text</span>
    </div>
</div>

<div class="form-group">
    {{ Form::label('date', 'Date', ['class' => 'control-label col-md-3']) }}
    <div class="col-md-9">
        {{ Form::text('date', null, ['placeholder' => 'hello world', 'class' => 'form-control']) }}
    </div>
</div>

{{ Form::close() }}

Even when I put the old value in like this it does not retain the old input

  {{ Form::text('name', old('name') , ['placeholder' => 'hello world' ,'class' => 'form-control']) }}

My method which stores the item in the back-end looks like this where ItemRequest takes care of validation.

public function store(ItemRequest $request, ImageMagick $imageMagick)
{
    $item = new Item;
    $item->name = $request->name;
    $item->description = $request->description;
    $item->date = $request->date;

    $item->save();
    return redirect()->route('some.other.route');
}

Trying to determine why old inputs are not being remembered.


Solution

  • Use withInput() method at the end of redirect route method, like this:

    // If validation failed, use this method to make the old inputs available in the view
    return redirect()->route('some.other.route')->withInput();
    

    See more about Old Inputs in Laravel

    Hope this helps!