83

How do I redirect back to my form page, with the given POST params, if my form action throws an exception?

Danny Kopping
  • 4,862
  • 2
  • 29
  • 38

10 Answers10

104

You can use the following:

return Redirect::back()->withInput(Input::all());

If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.

Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests:

return redirect()->to($this->getRedirectUrl())
                    ->withInput($request->input())
                    ->withErrors($errors, $this->errorBag());
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Danny Kopping
  • 4,862
  • 2
  • 29
  • 38
67

write old function on your fields value for example

<input type="text" name="username" value="{{ old('username') }}">
Vishal Rambhiya
  • 741
  • 6
  • 10
  • 1
    Thanks ! I am using Laravel 5.2 and this works for me too . Along with `old()` function in our blade template , we also need to use `withInput()` in our controller to make it work . Like => `if($validate->fails()) return redirect("somepage")->withErrors($validate)->withInput();` – nice_dev Mar 24 '16 at 10:49
  • 2
    Any idea on how to do this for `select` – Nitesh Verma Sep 25 '16 at 18:12
  • @NiteshVerma you can use jquery like `{{if(isset(old('select')){'$("select option[value=\''.old('select').'\']").attr("selected",true)'}};` – Naveen DA Nov 30 '17 at 05:11
  • Is there any solution similar to this for Laravel 4.2? – Debiprasad Mar 12 '18 at 11:41
  • how to do this on the select box ? – JuMa Apr 15 '21 at 04:23
32

In your HTML you have to use value = {{ old('') }}. Without using it, you can't get the value back because what session will store in their cache.

Like for a name validation, this will be-

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

Now, you can get the value after submitting it if there is error with redirect.

return redirect()->back()->withInput();

As @infomaniac says, you can also use the Input class directly,

return Redirect::back()->withInput(Input::all());

Add: If you only show the specific field, then use $request->only()

return redirect()->back()->withInput($request->only('name'));

Update: Get more example and real-life demonstration of Laravel form input here - https://devsenv.com/tutorials/how-to-redirect-back-in-laravel-with-form-input-and-many-possible-ways

Hope, it might work in all case, thanks.

Maniruzzaman Akash
  • 4,610
  • 1
  • 37
  • 34
8

this will work definately !!!

  $validation = Validator::make($request->all(),[
  'name' => ['Required','alpha']
  ]);
  
   if($validation->passes()){
     print_r($request->name);
   }
   else{
     //this will return the errors & to check put "dd($errors);" in your blade(view)
     return back()->withErrors($validation)->withInput();
   }
Aditya Tomar
  • 841
  • 1
  • 13
  • 20
7

You can use any of these two:

return redirect()->back()->withInput(Input::all())->with('message', 'Some message');

Or,

return redirect('url_goes_here')->withInput(Input::all())->with('message', 'Some message');

Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
  • Your answer does not add anything new to previous answers. Also it adds confusion because you do not explain what 'url' is. Also you already made an answer to this question. Please delete one of your answers . You can edit your own previous post. – Maxim Sagaydachny Jan 09 '20 at 06:43
6

I handle validation exceptions in Laravel 5.3 like this. If you use Laravel Collective it will automatically display errors next to inputs and if you use laracasts/flash it will also show first validation error as a notice.


Handler.php render:

public function render($request, Exception $e)
{
    if ($e instanceof \Illuminate\Validation\ValidationException) {
        return $this->handleValidationException($request, $e);
    }

    (..)
}

And the function:

protected function handleValidationException($request, $e)
    {
        $errors = @$e->validator->errors()->toArray();
        $message = null;
        if (count($errors)) {
            $firstKey = array_keys($errors)[0];
            $message = @$e->validator->errors()->get($firstKey)[0];
            if (strlen($message) == 0) {
                $message = "An error has occurred when trying to register";
            }
        }

        if ($message == null) {
            $message = "An unknown error has occured";
        }

        \Flash::error($message);

        return \Illuminate\Support\Facades\Redirect::back()->withErrors($e->validator)->withInput();
    }
Rav
  • 1,460
  • 1
  • 21
  • 33
5

Laravel 5:

return redirect(...)->withInput();

for back only:

return back()->withInput();
Luca C.
  • 11,714
  • 1
  • 86
  • 77
3

For Laravel 5

return redirect()->back()->withInput();

For Laravel 6, 7 and 8

return back()->withInput();

Docs:

Gass
  • 7,536
  • 3
  • 37
  • 41
1

You can try this:

return redirect()->back()->withInput(Input::all())->with('message', 'Something 
went wrong!');
Dino
  • 7,779
  • 12
  • 46
  • 85
Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
0
$request->flash('request',$request);

<input type="text" class="form-control" name="name" value="{{ old('name') }}">

It works for me.

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42