Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.8 on validation error return to specific view with all input -> old not working

TLDR;

(In Laravel 5.8) Upon validation error, how can I return to a specific view with all input and the errors?

I'm creating a multistep form in which I need to validate the input on each step. Therefore, I have created the first page as a create and then the subsequent pages to update.

On the second page, when the validator fails, I am returning the specific view as I want it to go to this partial and not the beginning of the form. I am also returning the errors and the input on fail.

Controller:

if ($validator->fails()) {
    return view('partials.question_02_' . $type)
        ->with('type', $type)
        ->with('id', $id)
        ->withErrors($validator)
        ->withInput($request->all());
}

Here is my validation logic:

$validator = Validator::make($request->all(), [
    'email'               => 'required',
    'first_name'          => 'required',
    'last_name'           => 'required',
    'phone'               => 'required',
]);

With this, I am able to go back to the specific view and with the validation errors. However, I am not able to receive the old input.

The following in Blade will show that there is an erro (the error class appears), however, it will not show the old input.

<input class="@if ($errors->has('first_name')) error @endif" 
type="text" name="first_name" placeholder="First Name" value="{{ old('first_name') }}">

*note, I only put it on two lines for legibility here

What is weird is that if I die and dump the request, I can see all of the input:

dd($request->all());

However, if I try to get it from the session, I don't see any of the input:

@if($errors)
    {{var_dump(Session::all())}}
@endif

Any idea why {{ old('first_name') }} isn't working in this case?

Thanks!

like image 618
Brad Ahrens Avatar asked Sep 01 '25 01:09

Brad Ahrens


1 Answers

You're Returning a view return view() instead you need to return redirect return redirect()as a return view will generate a fresh page and old() will not work.

So instead of

return view('partials.question_02_' . $type)

Use

return redirect()

&in your case

redirect()->action('LoginController@secondPage'); //you controller and method handling your second page 
like image 104
Aditya Thakur Avatar answered Sep 02 '25 16:09

Aditya Thakur