1.使用Form中的抽象方法
Illuminate\Foundation\Http\FormRequest
protected function getValidatorInstance()
{
$factory = $this->container->make('Illuminate\Validation\Factory');
if (method_exists($this, 'validator')) {
return $this->container->call([$this, 'validator'], compact('factory'));
}
return $factory->make(
$this->all(), $this->container->call([$this, 'rules']), $this->messages(), $this->attributes()
);
}
public function response(array $errors)
{
if ($this->ajax() || $this->wantsJson()) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
2.使用Controller中父类方法
App\Http\Controllers\Controller->Illuminate\Foundation\Validation\ValidatesRequests
validate->throwValidationException->buildFailedValidationResponse-> throw new HttpResponseException
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}
路由类Illuminate\Routing\Route
public function run(Request $request)
{
$this->container = $this->container ?: new Container;
try {
if (!is_string($this->action['uses'])) {
return $this->runCallable($request);
}
if ($this->customDispatcherIsBound()) {
return $this->runWithCustomDispatcher($request);
}
return $this->runController($request);
} catch (HttpResponseException $e) {
return $e->getResponse();
}
}
3.手动实装
$validator = Validator::make($request->all(),[
'title' => 'required',
'name' => 'required',
],[
'required' => ":attributeは必須となります。",
],[
'title' => 'タイトル',
'name' => '名前',
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
response()->json()->setJsonOptions(JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)->setData($validator->errors()->getMessages());