在 Laravel 中使用表单请求时如何检查验证是否失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48123558/
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 17:12:25  来源:igfitidea点击:

How to check if validation fail when using form-request in Laravel?

phplaravellaravel-5laravel-5.4laravel-5.5

提问by Junior

I am trying to write a CRUD for an API. However, when the validation fail, instead of redirecting the user to the home page, I want to return jsonbased response with the errors.

我正在尝试为 API 编写 CRUD。但是,当验证失败时,我想返回json基于错误的响应,而不是将用户重定向到主页。

I am able to do that using the following code

我可以使用以下代码来做到这一点

public function store(Request $request)
{
    try {
        $validator = $this->getValidator($request);

        if ($validator->fails()) {
            return $this->errorResponse($validator->errors()->all());
        }

        $asset = Asset::create($request->all());

        return $this->successResponse(
            'Asset was successfully added!',
            $this->transform($asset)
        );
    } catch (Exception $exception) {
        return $this->errorResponse('Unexpected error occurred while trying to process your request!');
    }
}

/**
 * Gets a new validator instance with the defined rules.
 *
 * @param Illuminate\Http\Request $request
 *
 * @return Illuminate\Support\Facades\Validator
 */
protected function getValidator(Request $request)
{
    $rules = [
        'name' => 'required|string|min:1|max:255',
        'category_id' => 'required',
        'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
        'purchased_at' => 'nullable|string|min:0|max:255',
        'notes' => 'nullable|string|min:0|max:1000',
    ];

    return Validator::make($request->all(), $rules);
}

Now, I like to extract some of my code into a form-requestto clean up my controller little more. I like to change my code to something like the code below.

现在,我喜欢将我的一些代码提取到 aform-request来清理我的控制器。我喜欢将我的代码更改为类似于下面的代码。

public function store(AssetsFormRequest $request)
{
    try {
        if ($request->fails()) {
            return $this->errorResponse($request->errors()->all());
        }            
        $asset = Asset::create($request->all());

        return $this->successResponse(
            'Asset was successfully added!',
            $this->transform($asset)
        );
    } catch (Exception $exception) {
        return $this->errorResponse('Unexpected error occurred while trying to process your request!');
    }
}

As you can probably tell that $request->fails()and $request->errors()->all()is not going to work. How can I check if the request failed and then how can I get the errors out of the form-request?

正如您可能会说的那样,$request->fails()并且 $request->errors()->all()不会起作用。如何检查请求是否失败,然后如何从表单请求中获取错误?

For your reference, here is how my AssetsFormRequestclass look like

供您参考,这是我的AssetsFormRequest课程的样子

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class AssetsFormRequest extends FormRequest
{
    /**
     * 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 [
            'name' => 'required|string|min:1|max:255',
            'category_id' => 'required',
            'cost' => 'required|numeric|min:-9999999.999|max:9999999.999',
            'purchased_at' => 'nullable|string|min:0|max:255',
            'notes' => 'nullable|string|min:0|max:1000',
        ];
    }
}

回答by Sohel0415

In your AssetFormRequestclass, you can overridefailedValidationmethod to the following-

在您的AssetFormRequest类中,您可以将failedValidation方法覆盖为以下内容-

public $validator = null;
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $this->validator = $validator;
}

Then your controller method, do anything you want with your $validatorobject. May be something like the following-

然后你的控制器方法,用你的$validator对象做任何你想做的事情。可能类似于以下内容-

if (isset($request->validator) && $request->validator->fails()) {
        return response()->json($request->validator->messages(), 400);
    }

You can see thislink too for further details. Hope it helps :)

您也可以查看链接以获取更多详细信息。希望能帮助到你 :)

回答by PHP Worm...

Add this function to your Request:

将此功能添加到您的请求中:

public function withValidator($validator)
    {
        if ($validator->fails()) {
            Session::flash('error', 'Flash error!');
        } else {

        }

    }