• [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:/^1d{10}$/',
                'city_code' => 'required|numeric',
            ],[
                'required'=>":attribute 字段必填",
                'numeric'=>":attribute 字段必须为数字",
                'regex'=>":attribute 字段手机号格式不正确",
            ]);
            return $validateData;
        }
    
        /**
         * 同步线索质检
         * @param Request $request
         * @return IlluminateHttpJsonResponse
         */
        public function sync(Request $request){
            $validateData=$this->checkRequestParam($request);
            return $this->responseSuccess($validateData);
        }

    效果如这样

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

    <?php
    
    namespace AppExceptions;
    
    use AppLibApiHelperApiCode;
    use IlluminateFoundationExceptionsHandler as ExceptionHandler;
    use IlluminateSupportArr;
    use IlluminateSupportFacadesApp;
    use IlluminateValidationValidationException;
    use SymfonyComponentHttpKernelExceptionHttpException;
    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);
        }
    }

    开源作品

    GO-FLY,一套可私有化部署的免费开源客服系统,安装过程不超过五分钟(超过你打我 !),基于Golang开发,二进制文件可直接使用无需搭开发环境,下载zip解压即可,仅依赖MySQL数据库,是一个开箱即用的网页在线客服系统,致力于帮助广大开发者/中小站长快速整合私有客服功能
    github地址:go-fly
    官网地址:https://gofly.sopans.com
  • 相关阅读:
    [leetcode]N-Queens II
    基于Linux的智能家居的设计(4)
    eclipse集成Python开发环境
    创业三年,离开公司,请各位看一下我的简历,指点一下未来的路
    Jquery实现选项卡功能
    R语言中两个数组(或向量)的外积怎样计算
    《Java程序猿面试笔试宝典》之组合与继承有什么差别
    Sublime Text3打造U盘便携Lua IDE
    php Laravel 框架之建立后台目录
    树的同构(25 分)
  • 原文地址:https://www.cnblogs.com/taoshihan/p/15294102.html
Copyright © 2020-2023  润新知