首页 > 开发 > PHP > 正文

Laravel学习教程之request validation的编写

2024-05-04 22:45:01
字体:
来源:转载
供稿:网友

前言

本文主要给大家介绍了关于Laravel之request validation编写的相关内容,在用laravel写api时,当前端传进来的request是POST/PUT/PATH等method时,那需要做request validation,尽管对于前后端分离程序,前端程序Angular/Vue已经做了validation,但是ajax传过来的json input,在后端也需要做validation。

那该如何优雅的编写request validation呢?laravel官方文档已经包含了这个feature: Form Request Validation

实现方法如下

这里可以写一个JsonRequest:

class JsonRequest extends Illuminate/Foundation/Http/FormRequest{ public function rules() {  $method = $this->method();    assert(in_array($method, [static::METHOD_POST, static::METHOD_PUT, static::METHOD_PATCH], true));    $controller = $this->route()->getController();  $rules  = $controller::RULES;  return ($rules[$this->method()] ?? []) + ($rules['*'] ?? []); } public function authorize() {  return true; }}

这样就可以在众多Model Controller里使用JsonRequest就行,如:

use Illuminate/Http/Request;final class AccountController extends /App/Http/Controllers/Controller{ public const RULES = [  Request::METHOD_POST => [   'bank_account' => 'required_if:type,bank',   'loan_account' => 'required_if:type,loan',  ],  Request::METHOD_PUT => [   // ...  ],  '*' => [   // ...  ], ];}

这样就可以校验前端传进来的json input是否合法。

(1)如果前端传进来的json input是:

{ "name": "lx1036", "type": "loan", "bank_account": {  "source": "bank", }}

那就validation失败,不合法。

(2) 如果前端传进来的json input是:

{ "name": "lx1036", "type": "bank", "loan_account": {  "source": "loan", }}

那就validation失败,不合法。

这样就可以校验json input,不合法就直接弹回throw 一个HttpException,不再用在进入下一步逻辑。对于这样嵌套的json input,使用request validation来校验对象间关系很重要,可以看做是进入核心业务逻辑前的初步校验。。当然最后写表时还有model validation,避免坏数据进入db。

最后一点,laravel文档只是说了用法,没有说明原理。代码在/Illuminate/Foundation/Providers/FormRequestServiceProvider::class:

 public function boot() {  // /Illuminate/Foundation/Http/FormRequest use 了 ValidatesWhenResolvedTrait,extends 了 /Illuminate/Contracts/Validation/ValidatesWhenResolved  $this->app->afterResolving(ValidatesWhenResolved::class, function ($resolved) {   $resolved->validate();  });  // ... }

所以当从容器中resolve完/Illuminate/Foundation/Http/FormRequest后就会立即执行/Illuminate/Foundation/Http/FormRequest::validate()方法,具体不详述,可看laravel源码。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表