Validating and then redirecting to a post route in Laravel

laravel, php, redirect, validation

Solution

This isn't particularly a Laravel issue, this requires you to understand how HTTP redirects work. When you send a redirect to a browser, you are sending the browser a 302 redirect with a URL to redirect to. Browsers will redirect making a GET request to the URL provided. You could potentially change the response code to 307 which asks the browser to do the redirect with the same method as was originally called with a security message but it is a bad idea to rely on this as it is implemented differently across browsers. Also Laravel would require you to build a custom response object with your own headers.

To keep your code compatible across browsers it is better practice to separate GET and POST logic. This is why returning views directly from a POST route is generally a bad idea.

The way I see this you really need to be looking to re-factor and rework how your forms work if you want the functionality you are aiming for.

Problem

Is it possible to redirect the user to a POST route in Laravel. I have 2 forms. form-one is sent to the Route containing form-two and form-two is sent to the final Route and then it is validated. If `$validator->fails()` for form-two is a truthy value at the final Route I want to send the user back to from-two but it is a POST Route. ``` Redirect::to('Form-Two')->withErrors($validator); ``` I tried using this but it failed maybe because it only works for Get routes. One thing I thought of doing was to redirect the user to a Get Route and then post the data to form-two from that Get Route, but that sounds stupid. Is there any cleaner way to do this. I'm a newbie. Form Two: ``` Route::post('form-two', array('before' => 'csrf', function() { $formOneData= Input::all(); $rules = array(...); $validator = Validator::make($formOneData, $rules); if ($validator->fails()) { return Redirect::to('Form-One')->withErrors($validator); } } ``` Final Page: ``` Route::post('final', array('before' => 'csrf', function() { $finalData = Input::all(); $rules = array(...); $validator = Validator::make($finalData, $rules); if ($validator->fails()) { return Redirect::to('Form-Two')->withErrors($validator); } } ```

Original source