Laravel 5更改表单请求失败的验证行为

Kha*_*jan 6 php api json laravel laravel-5

我有一个表单请求来验证注册数据.该应用程序是一个移动API,我希望这个类在验证失败的情况下返回格式化的JSON,而不是默认情况下(重定向).

我尝试failedValidationIlluminate\Foundation\Http\FormRequest类中重写该方法.但这似乎不起作用.有任何想法吗?

码:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Contracts\Validation\Validator;

class RegisterFormRequest extends Request {

/**
 * 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 [
        'email' => 'email|required|unique:users',
        'password' => 'required|min:6',
    ];
}

}
Run Code Online (Sandbox Code Playgroud)

Bal*_*ran 6

无需覆盖任何功能。只要您添加

Accept: application/json
Run Code Online (Sandbox Code Playgroud)

在表单标题中。Laravel将以相同的URL和JSON格式返回响应。


pin*_*sia 3

通过查看 中的以下函数Illuminate\Foundation\Http\FormRequest,Laravel 似乎可以正确处理它。

    /**
     * Get the proper failed validation response for the request.
     *
     * @param  array  $errors
     * @return \Symfony\Component\HttpFoundation\Response
     */
    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);
    }
Run Code Online (Sandbox Code Playgroud)

根据下面wantsJson的功能Illuminate\Http\Request,您必须明确寻求JSON响应,

    /**
     * Determine if the current request is asking for JSON in return.
     *
     * @return bool
     */
    public function wantsJson()
    {
        $acceptable = $this->getAcceptableContentTypes();

        return isset($acceptable[0]) && $acceptable[0] == 'application/json';
    }
Run Code Online (Sandbox Code Playgroud)