How to redirect back to form with input - Laravel 5

后端 未结 9 1197
离开以前
离开以前 2020-12-01 02:53

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

9条回答
  •  粉色の甜心
    2020-12-01 03:19

    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();
        }
    

提交回复
热议问题