Laravel 5.5 FormRequest 自定義錯誤消息
使用FormRequest進行表單驗證,就不用讓驗證邏輯和控制器里面的邏輯都混在一起。但在使用的時候呢,發現json錯誤返回的數據,與我們想要的有點差距。下面我給個例子:(不喜勿噴)
在用ajax進行提交時,如果驗證錯了,那么他會返回
如果是權限錯了,他會返回
但我想要的是
那怎么辦呢,其實很簡單
我們只需要在 App\Exceptions\Handler 里面重寫兩個函數就可以了
添加上這兩個函數,然后里面怎么定義,就看你了
記得加上
use Illuminate\Validation\ValidationException; use Illuminate\Auth\Access\AuthorizationException;
最后附上這兩個文件的代碼
LoginPost
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Auth\AuthenticationException; class LoginPost extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize(){ if($this->input('account')=='aaa@abc.com'){ return false; } return true; } protected function failedAuthorization() { throw new AuthenticationException('該帳號已被拉黑'); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules(){ return [ 'account'=>[ 'required', 'regex:/^1[34578][0-9]\d{4,8}|(\w)+(\.\w+)*@(\w)+((\.\w+)+)|[0-9a-zA-Z_]+$/',//驗證為手機號,郵箱,或帳號 ], 'password'=>'required|between:6,18',//驗證密碼 ]; } public function messages(){ return [ 'account.required' => '帳號不能為空', 'account.regex' => '帳號不合法', 'password.required' => '密碼不能為空', 'password.between' => '密碼錯誤', ]; }
Handler
<?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Validation\ValidationException; use Illuminate\Auth\AuthenticationException; class Handler extends ExceptionHandler { /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'password', 'password_confirmation', ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $exception * @return void */ public function report(Exception $exception) { parent::report($exception); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { return parent::render($request, $exception); } protected function unauthenticated($request, AuthenticationException $exception) { if($request->expectsJson()){ $response=response()->json([ 'status'=>3, 'msg' => $exception->getMessage(), 'errors'=>[], ], 200); }else{ $response=redirect()->guest(route('login')); } return $response; } protected function invalidJson($request, ValidationException $exception) { return response()->json([ 'status'=>2, 'msg' => $exception->getMessage(), 'errors' => $exception->errors(), ], $exception->status); } }
--------------------- 本文來自 斷水流灬 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/duanshuiliu2017/article/details/78343408?utm_source=copy