Browse Source

add validation to exception handler

Taylor Otwell 6 years ago
parent
commit
3310063b59
1 changed files with 20 additions and 1 deletions
  1. 20 1
      app/Exceptions/Handler.php

+ 20 - 1
app/Exceptions/Handler.php

@@ -4,6 +4,7 @@ namespace App\Exceptions;
 
 use Exception;
 use Illuminate\Auth\AuthenticationException;
+use Illuminate\Validation\ValidationException;
 use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
 
 class Handler extends ExceptionHandler
@@ -43,7 +44,25 @@ class Handler extends ExceptionHandler
     }
 
     /**
-     * Convert an authentication exception into an unauthenticated response.
+     * Convert a validation exception into a response.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  Illuminate\Validation\ValidationException  $exception
+     * @return \Illuminate\Http\Response
+     */
+    protected function invalid($request, ValidationException $exception)
+    {
+        $errors = $exception->validator->errors()->messages();
+
+        return $request->expectsJson()
+                    ? response()->json(['message' => $exception->getMessage(), 'errors' => $errors])
+                    : redirect()->back()->withInput()->withErrors(
+                            $errors, $exception->errorBag
+                      );
+    }
+
+    /**
+     * Convert an authentication exception into a response.
      *
      * @param  \Illuminate\Http\Request  $request
      * @param  \Illuminate\Auth\AuthenticationException  $exception