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

时间:2015-05-29 11:05:26

标签: php json api laravel laravel-5

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

我尝试从failedValidation类重写方法Illuminate\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',
    ];
}

}

4 个答案:

答案 0 :(得分:5)

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

Accept: application/json

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

答案 1 :(得分:2)

通过查看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);
    }

根据以下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';
    }

答案 2 :(得分:0)

这是我的解决方案,它在我的最终运作良好。我添加了请求代码下面的函数:

public function response(array $errors)
{
    if ($this->ajax() || $this->wantsJson())
    {
        return Response::json($errors);
    }

    return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors, $this->errorBag);
}

响应函数可以很好地处理laravel。如果你请求json或ajax,它会自动返回。

答案 3 :(得分:0)

只需在您的请求中添加以下功能:

use Response;
public function response(array $errors)
{
      return Response::json($errors);    
}
相关问题