【问题标题】:How to check if validation fail when using form-request in Laravel?在 Laravel 中使用表单请求时如何检查验证是否失败?
【发布时间】:2018-06-15 20:29:14
【问题描述】:

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

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

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

现在,我想将我的一些代码提取到 form-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!');
    }
}

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

供您参考,这是我的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',
        ];
    }
}

【问题讨论】:

标签: php laravel laravel-5 laravel-5.4 laravel-5.5


【解决方案1】:

在您的 AssetFormRequest 类中,您可以将 override failedValidation 方法改为以下 -

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

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

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

您也可以查看this 链接了解更多详情。 希望对你有帮助:)

【讨论】:

    【解决方案2】:

    将此函数添加到您的请求中:

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

    【讨论】:

    • 我认为这种方法更像是一个 Http 错误,而不仅仅是一个 flash 消息,不是吗?
    • 我在成功请求操作后使用此方法。好技巧!
    【解决方案3】:

    已经 2 年了,但也许这会对某人有所帮助。

    您可以通过添加(在 Laravel 6.0.4 中测试)来覆盖 AssetFormRequest 中的 getValidatorInstance() 方法:

    use Illuminate\Contracts\Container\BindingResolutionException;
    use Illuminate\Contracts\Validation\Factory as ValidationFactory;
    use Illuminate\Contracts\Validation\Validator;
    
    /**
     * Get the validator instance for the request.
     *
     * @return Validator
     * @throws BindingResolutionException
     */
    public function getValidatorInstance()
    {
        if ($this->validator) {
            return $this->validator;
        }
    
        $factory = $this->container->make(ValidationFactory::class);
    
        if (method_exists($this, 'validator')) {
            $validator = $this->container->call([$this, 'validator'], compact('factory'));
        } else {
            $validator = $this->createDefaultValidator($factory);
        }
    
        if (method_exists($this, 'withValidator')) {
            $this->withValidator($validator);
        }
    
        $this->setValidator($validator);
    
        return $this->validator;
    }
    

    之后,您可以在控制器中使用验证器:

    public function store(AssetsFormRequest $request)
    {
        $validator = $request->getValidatorInstance();
    
        try {
            if ($validator->fails()) {
                return $this->errorResponse($validator->errors());
            }            
            $asset = Asset::create($validator->validated());
    
            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!');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-11
      • 2020-06-13
      • 1970-01-01
      • 2019-10-19
      • 2016-10-21
      • 2016-04-13
      • 1970-01-01
      • 2015-08-12
      相关资源
      最近更新 更多