laravel 写api的时候自定义错误消息

在方法里面捕获错误:

页面:
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, '更新失败!');
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值