首页 > 其他分享 >laravel 验证规则封装

laravel 验证规则封装

时间:2022-11-08 13:56:50浏览次数:59  
标签:laravel function 封装 验证 required location return document public

1.先编写基类 baseRequest.php

<?php

namespace App\validate;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class BaseRequest extends FormRequest
{


    public function rules(){
        $rule_action = "getRulesBy".ucfirst($this->route()->getActionMethod());
        if(method_exists($this,$rule_action)){
            return $this->$rule_action();
        }

    }

    public function getDefaultRules(): array
    {
        return [];
    }

    public function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            "code"=> 0,
            "msg" => $validator->errors()->first()
        ]));
        //parent::failedValidation($validator); // TODO: Change the autogenerated stub
    }

}

  2.业务验证类 PostRequest .php

<?php

namespace App\validate;

class PostRequest extends BaseRequest
{

    public function getRulesByBing2(){
        return [
            'title' => "required|min:4",
            'body'  => 'required'
        ];
    }

    public function messages()
    {
        return [
            'title.required' => '标题一定要有',
            'body.required' => 'BODY一定要有',
            'title.min'=> '不能少于4'
        ];
    }

}

  3.控制器里的写法

public function bing2(PostRequest $request){
        echo "success";
    }

  

 

 

 

 

 

 

 

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:laravel,function,封装,验证,required,location,return,document,public
From: https://www.cnblogs.com/bing2017/p/16869435.html

相关文章