首页 文章

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

提问于
浏览
6

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

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

码:

<?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 回答

  • 1

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

    并且根据 Illuminate\Http\Request 中的 wantsJson 函数,您必须明确地寻求 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';
        }
    
  • 0

    无需覆盖任何功能 . 只是你添加了

    Accept: application/json
    

    在您的表单 Headers 中 . Laravel将以相同的URL和JSON格式返回响应 .

  • 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,它将自动返回 .

  • 4

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

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

相关问题