网站首页
Laravel--API-提交表单使用Request前置表单验证
发布时间:2019-05-29 08:17查看次数:2684
Laravel--API-提交表单使用Request前置表单验证
自定义返回数据JSON数据结构
作用:在做API层表单验证
自动实时返回JSON结构数据
在用POSTMAN 调试接口 需要在头部加入模拟AJAX的头
要不然就跳页面了
<?php
namespace App\Http\Requests\Request;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
class ProxyUser extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
protected $message;
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
"account"=>"required",
"password"=>"required",
"proxyname"=>"required",
"shangwu"=>"required",
];
}
/**
* @apiName failedValidation
* @apiDescription 重写表单验证失败后方法
* @param Validator $validator
*/
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json($this->response($validator->errors()->toArray())));
}
public function response(array $errors){
if (($this->ajax() && ! $this->pjax()) || $this->wantsJson()) {
$errorsmsg = [];
foreach($errors as $k => $v){
$errorsmsg["data"][$k] = $v[0];
}
$errorsmsg["code"] = 9800;
$errorsmsg["message"] = "表单验证失败";
return $errorsmsg;
}
}
public function messages()
{
$array = [
"account.required"=>"渠道账号 不能 为空",
"password.required"=>"渠道密码 不能 为空",
"proxyname.required"=>"渠道名称 不能 为空",
"shangwu.required"=>"所属商务 不能 为空",
];
return $array;
}
}
关键字词:laravel##