[laravel] laravel验证请求参数

laravel 验证请求参数,有自带的规则,如果有特殊的规则,可以自己写正则验证逻辑

比如验证手机号

在控制器文件中可以直接这样编写

默认情况下,如果验证通过,你的代码会继续正常运行。如果验证失败,则会抛出异常,并自动将对应的错误响应返回给用户。 在传统 HTTP 请求下,会生成一个重定向响应, 而对于 AJAX 请求则会发送 JSON 响应,这里的JSON响应必须得传递指定的JSON header头才行

这里我修改了异常处理类,继承类覆盖了render方法,直接全部返回json数据

class QualityController extends Controller
{
    /**
     * 检测参数
     * @param Request $request
     * @return bool
     */
    protected function checkRequestParam(Request $request):array {
        $validateData=$request->validate([
            'phone' => 'required|regex:/^1\d{10}$/',
            'city_code' => 'required|numeric',
        ],[
            'required'=>":attribute 字段必填",
            'numeric'=>":attribute 字段必须为数字",
            'regex'=>":attribute 字段手机号格式不正确",
        ]);
        return $validateData;
    }

    /**
     * 同步线索质检
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sync(Request $request){
        $validateData=$this->checkRequestParam($request);
        return $this->responseSuccess($validateData);
    }

效果如这样

 

 

有需求的可以参考下面的例子自行修改

<?php

namespace App\Exceptions;

use App\Lib\ApiHelper\ApiCode;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;

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 = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
    public function report(Throwable $e)
    {
        $message = [
            'Time:' . now(),
            'Environment:' . config('app.env'),
            'Project Name:' . config('app.name'),
            'Url:' . request()->url(),
            'Request:' . http_build_query(request()->all()),
            'Exception:' . get_class($e) . '(code:' . $e->getCode(). '): ' . $e->getMessage() .
            ' at ' . $e->getFile() . ':' . $e->getLine(),
            'Exception Trace:' . $e->getTraceAsString(),
        ];
        logger()->error('Exception handler.', $message);

        try {
            if ($this->shouldntReport($e) && App::environment('production')) {
                $message = [
                    'Environment:' . config('app.env'),
                    'Project Name:' . config('app.name'),
                    'Url:' . request()->url(),
                    'Request:' . http_build_query(request()->all()),
                    'Exception:' . get_class($e) . '(code:' . $e->getCode(). '): ' . $e->getMessage() .
                    ' at ' . $e->getFile() . ':' . $e->getLine(),
                ];
            }
        } catch (\Exception $exception) {
            logger()->error($exception->getMessage());
        }

        parent::report($e);
    }

    public function render($request, Throwable $e)
    {
        switch ($e) {
            case $e instanceof ValidationException:
                $response = [
                    'errmsg' => Arr::first($e->errors())[0] ?? '请求参数不合法',
                    'errcode' => ApiCode::ERROR_UNPROCESSABLE_ENTITY,
                    'data' => new \stdClass()
                ];

                break;
            case $e instanceof HttpException:
                $response = [
                    'errmsg' => ApiCode::getMessage(ApiCode::ERROR_HTTP_REQUEST),
                    'errcode' => ApiCode::ERROR_HTTP_REQUEST,
                    'data' => new \stdClass()
                ];

                break;
            case $e instanceof ApiException:
                $response = [
                    'errmsg' => $e->getMessage(),
                    'errcode' => ApiCode::ERROR_API_REQUEST,
                    'data' => new \stdClass()
                ];

                break;
            default:
                $code = $e->getCode() ?: ApiCode::ERROR_SERVER_INTERNAL;
                $response = [
                    'errmsg' => $e->getMessage() ?: ApiCode::getMessage($code),
                    'errcode' => $code,
                    'data' => new \stdClass()
                ];
        }

        if (config('app.debug')) {
            $response['exception'] = get_class($e);
            $response['message'] = $e->getMessage();
            $response['trace'] = $e->getTrace();
        }

        return response()->json($response, 200);
    }
}

 

posted @ 2021-09-16 16:27  唯一客服系统开发笔记  阅读(460)  评论(0编辑  收藏  举报