fightstarr20
fightstarr20

Reputation: 12598

Laravel 5.6 - Form not re-populating with previous values after validation

I have a simple form in Laravel 5.6 which I am running validation on, my form looks like this..

   @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

<form action="{{route('posts.store')}}" method="POST">
   <input name="title" type="text">#
    <button type="submit" class="btn btn-success">Submit</button>
</form>

And my controller like this..

public function store(Request $request)
    {

        $this->validate($request, [
            'title' => 'required',
        ]);

        $post = new Post;
        $title = $request->input('title');
        $post->save();
    }

This is working but when the validation fails and the error message is displayed, it does not repopulate the form with the previous values. Reading the docs at https://laravel.com/docs/5.2/requests#old-input it says I shouldn't have to do anything and it will be automatic.

Anyone any ideas where I am going wrong?

Upvotes: 5

Views: 3230

Answers (2)

Marwelln
Marwelln

Reputation: 29413

If you want to keep the previous input, you need to use the old helper function, as seen in the documentation of your link if you scroll down to "Retrieve old input".

You need to change your input to the following:

<input name="title" type="text" value="{{ old('title') }}">

Where title matches the value your have in the name attribute of your input.

Upvotes: 6

Niellles
Niellles

Reputation: 878

You're not echoing a value in your view. I am 99% sure that the following checks isset().

<input name="title" type="text" value="{{$name}}">#

Just make sure that $request->name is passed from your controller to your view, although that may just be the "automated" part that you were talking about... I'll have to check the docs.

Upvotes: 0

Related Questions