Laravel form request validation on store and update use same validation

≯℡__Kan透↙ 提交于 2021-01-28 13:39:25

问题


I create laravel form validation request and have unique rules on that validation.

I want use it on store and update method without create new form request validation again.

but the problem is when on store the id doesnt exist and the validate is passed and when on update i failed the pass the validating because the id is exist on storage

i want to ignore the id on unique rules but use same form validate request

what is best practice to check on form validate request class if this action from store or update method to ignore unique id ?


回答1:


Ok.. i can do it like @porloscerros Ψ suggest

    public function rules()
    {
        $rules = [
            'name' => 'required|string|unique:products|max:255',
        ];

        if (in_array($this->method(), ['PUT', 'PATCH'])) {
            $product = $this->route()->parameter('product');

            $rules['name'] = [
                'required',
                'string',
                'max:255',
                Rule::unique('loan_products')->ignore($product),
            ];
        }

        return $rules;
    }



回答2:


Why are you checking the id when store or update in FormRequest? You don't need this. The id comes to your controller's method like as parameter. Or laravel will create the model using DI in the your controller's method public function update(User $user) and then you can use $user like an instance of User model. You may check the id in web.php or api.php: https://laravel.com/docs/7.x/routing#parameters-regular-expression-constraints

And I suggest you not to use one FormRequest for two methods. This is bad practice



来源:https://stackoverflow.com/questions/61543013/laravel-form-request-validation-on-store-and-update-use-same-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!