laravel write api when a custom error message

Copyright: the voice of experience, I do not know whether the change package spicy bar, and the other, please indicate the source. https://blog.csdn.net/zhezhebie/article/details/89740091

Inside method to trap the error:

Page:
https://blog.csdn.net/zhezhebie/article/details/78500326

api inside:

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

Then I wrote the above piece of code that needs to be verified in all places, and now think quite silly actually using the request () -> validate () when, if there is abnormal, it will throw a ValidationException, and so we can make global capture anomalies in there !!!

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

Now, we can use the same method as in the verification components inside and web! Is not that great!

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, '更新失败!');
}

Guess you like

Origin blog.csdn.net/zhezhebie/article/details/89740091