在方法里面捕获错误:
页面:
https://blog.csdn.net/zhezhebie/article/details/78500326
api里面:
$inputs = $request->all();
$validator = Validator::make($inputs, [
'email' => 'required|email',
'password' => 'required|string|min:6|max:20',
]);
if ($validator->fails()) {
$error = $validator->errors()->first();
return outPutJson('', 201, $error);
}
然后我就在所有需要验证的地方写了上面那一段代码,现在想想蛮傻的.其实使用request()->validate()的时候,如果有异常,是会抛出一个ValidationException的,这样的话我们就可以在异常那里进行全局捕获!!!
D:\phpStudy\PHPTutorial\WWW\xxx\app\Exceptions\Handler.php
if ($exception instanceof ValidationException) {
if (substr($_SERVER['REQUEST_URI'], 1, 3) == 'api') {
$error = $exception->validator->errors()->first(); #参考下面的两个文件
return outPutJson('', 201, $error);
}
}
D:\phpStudy\PHPTutorial\WWW\xxx\vendor\laravel\framework\src\Illuminate\Validation\ValidationException.php
D:\phpStudy\PHPTutorial\WWW\xxx\vendor\laravel\framework\src\Illuminate\Support\MessageBag.php
现在,我们就可以在方法里面和web那样一样使用验证组件了!是不是很棒!
public function updateUserInfo(Request $request) {
$user = auth()->user();
$attributes = request()->validate(
[
'email' => 'required|email|unique:users,email,' . $user->id, #排除自己
'telephone' => 'required|string|min:6|max:20',
'nick_name' => 'required|string|min:1|max:20',
'birthday' => 'required|date|before:8 years ago',
], [
'birthday.before' => '亲爱的小仙女,人家8岁的时候在玩泥巴呢~',
]);
if ($user->update($attributes)) {
return outPutJson();
}
return outPutJson('', 201, '更新失败!');
}