自定义laravel表单请求验证类(FormRequest共用一个rules())
class TeamDataPermissionRequest extends BaseRequest
{
public $mid='';
public $work_wechat=[];
public function __construct()
{
$this->mid=Auth::user()->mid;
$path = \Request::getPathInfo();
$method = \Request::method();
$path_method=$path.'/'.$method;
// 根据路径判断验证场景
switch ($path_method) {
case '/api/workwechat/team/permission_member/POST':
$this->scene = 'add';
break;
case '/api/workwechat/team/permission_member/PUT':
$this->scene = 'put';
break;
case '/api/workwechat/team/permission_member/GET':
$this->scene = 'get';
break;
}
}
/**
* 验证规则
*
* @var array
*/
protected $rules = [
'default' => [],
'add' => [
'name'=> 'required|filled',
'email' => 'required|filled|email',
'password' => 'required|filled',
'confirm_password'=> 'required|filled|same:password',
'role' => 'required|filled',
'channel' => 'required|filled|array',
'status'=> 'required|filled',
'sale_uuid'=>'required|filled',
'user_id'=>'required|filled',
],
'put'=>[
'name'=> 'required|filled',
'email' => 'required|filled|email',
'role' => 'required|filled',
'channel' => 'required|filled|array',
'status'=> 'required|filled',
'sale_uuid'=>'required|filled',
'admin_id'=>'required|filled',
],
'get'=>[
'sales_uuid' => 'required|filled',
'admin_id'=>'required|filled',
]
];
protected $messages = [
'add'=>[
"name.required" => "添加名称必填"
],
'put'=>[
"name.required" => "名称必填"],
];
创建 基础request验证,根据路由和方法名使用不同的验证规则和验证提示信息
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BaseRequest extends FormRequest
{
/**
* 验证规则场景
*
* @var string
*/
protected $scene = 'default';
/**
* 验证规则
*
* @var array
*/
protected $rules = [];
/**
* 验证错误消息
*
* @var array
*/
protected $messages =[];
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return $this->rules[$this->scene];
}
/**
* Get the validation messages that apply to the request.
*
* @return array
*/
public function messages()
{
return $this->messages[$this->scene] ?? $this->messages;
}
}
前后端分离的在App\Exceptions异常 中的??render方法加上验证导致抛出异常的处理 返回json
namespace App\Exceptions;
class Handler extends ExceptionHandler
{
public function render($request, Exception $exception)
{
if ($exception instanceof ValidationException) {
$errors = $exception->errors();
$errors = array_collapse($errors);
$error = array_first($errors);
return response(['code' => RET_CODE_FAIL, 'message' => $error, 'data' => []], 200);
}
}
|