<?php
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
class ExampleRequest extends FormRequest
{
/**
* 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 [
'title' => 'required|max:20',
'name' => ['required', new Uppercase()],
];
}
/**
* 获取已定义的验证规则的错误消息。
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'A title is required',
'title.max' => 'The title may not be greater than 20 characters.',
];
}
/**
* 兼容 form 表单请求与 ajax 请求或者 json api 请求
* 验证失败,返回错误信息
*
* @param Validator $validator
* @throws
*/
protected function failedValidation(Validator $validator)
{
if ($this->wantsJson() || $this->ajax()) {
throw new HttpResponseException(
new JsonResponse([
'code' => 500,
'msg' => $validator->errors()->first(),
'data' => new \stdClass()
])
);
} else {
parent::failedValidation($validator);
}
}
}
在控制器中使用 ExampleRequest
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests\ExampleRequest;
class ExampleController extends Controller
{
public function valid(ExampleRequest $request)
{
$params = $request->all();
dd($params);
}
}