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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30527953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:39:42  来源:igfitidea点击:

Laravel 5 change form request failed validation behavior

phpjsonapilaravellaravel-5

提问by Khalid Dabjan

I have a form request to validate registration data. The application is a mobile API and I would like this class to return formatted JSON in case of a failed validation instead of what it does by default (redirection).

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

I tried overriding the method failedValidationfrom Illuminate\Foundation\Http\FormRequestclass. but that doesn't seem to work. Any ideas?

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

Code:

代码:

<?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',
    ];
}

}

采纳答案by pinkal vansia

By looking at following function in Illuminate\Foundation\Http\FormRequest, it seems Laravel handles it properly.

通过查看 中的以下函数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);
    }

And as per wantsJsonfunction in Illuminate\Http\Requestbelow, you must explicitly seek JSONresponse,

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

回答by Balachandiran

No need override any function. just you add the

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

Accept: application/json

In your form header. Laravel will return the response in same URL and in JSON format.

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

回答by Kuya A

This is my solution and it is working well in my end. I added the function below Request code:

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

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);
}

The response function handle well by laravel. It will automatically return if you request json or ajax.

响应函数由 laravel 处理得很好。如果您请求 json 或 ajax,它将自动返回。

回答by Rahul Gaikwad

Just add the following function on your Request:

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

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