Laravel 5.5 更新时的条件表单请求验证规则

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

Laravel 5.5 conditional form request validation rule on update

phplaravellaravel-5laravel-validationlaravel-5.5

提问by Dorin Niscu

I created a validation rule for the image form.

我为图像表单创建了一个验证规则。

It works fine on store method but I do not want the image field to be required on update because I may only update the title for example.

它在 store 方法上运行良好,但我不希望更新时需要图像字段,因为例如我可能只更新标题。

class ImageRequest extends Request
{   
    /**
     * Rules array
     */
    protected $rules = [
        'title' => 'required|string|between:3,60',
        'alt'   => 'sometimes|string|between:3,60',
        'image' => 'required|image|max:4000|dimensions:min_width=200,min_height=200',
    ];

    /**
     * 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 $this->rules;
    }
}

For uniquevalidation we can add custom query conditions:

对于唯一验证,我们可以添加自定义查询条件:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')

or

或者

'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1);
})

Is it a clean way to achieve something similar for required?

这是一种实现类似required的干净方法吗?

Apply requiredonly for new images.

申请要求仅适用于新的图像。

采纳答案by Dorin Niscu

I found a solution.

我找到了解决办法。

I renamed imageinto file.

我将image重命名为file

The route is homestead.app/images/1on updateand homestead.app/imageson storeso the $imageproperty will be $this->image = 1on updateand $this->image = nullon store.

路线是homestead.app/images/1更新homestead.app/images商店所以$image属性将是$this->image = 1更新$this->image = nullstore

class ImageRequest extends Request
{
    /**
     * Rules array
     */
    protected $rules = [
        'title'=> 'required|string|between:3,60',
        'alt'  => 'sometimes|string|between:3,60',
        'file' => [
            'image',
            'max:4000',
            'dimensions:min_width=200,min_height=200',
        ],
    ];

    /**
     * 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()
    {
        $this->rules['file'][] = is_null($this->image) ? 'required' : 'sometimes';

        return $this->rules;
    }
}

回答by iCoders

you Can use switch statement inside rule

您可以在规则中使用 switch 语句

 public function rules()
    {

        switch ($this->method()) {
            case 'GET':
            case 'DELETE': {
                return [];
            }
            case 'POST': {

                      return [
                          'first_name'=>'required',
                          'last_name'=>'required',
                        'email'=>'required|email|unique:users,email,'.$this->id,
                          'password'=>'',
                          'dob'=>'required',
                          'phone_one'=>'required',
                          'phone_two'=>'required',
                          //'user_role'=>'required',
                      //    'profile_image'=>'required'
                      ];
            }
            case 'PUT':
            case 'PATCH': {
                return [

                ];
            }
            default:break;
        }

Also you can use condtion like on update yuo have id so based on that you can check whether its update or insert since on insert you dont have id so

你也可以使用条件,比如更新你有 id 所以基于此你可以检查它是更新还是插入,因为在插入时你没有 id 所以

回答by madalinivascu

Create another class that extends the Request class, DI that into your update controller action

创建另一个扩展请求类的类,DI 到您的更新控制器操作

class UpdateImageRequest extends Request
{   
    /**
     * Rules array
     */
    protected $rules = [
        'title' => 'required|string|between:3,60',
        'alt'   => 'sometimes|string|between:3,60'
    ];

    /**
     * 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 $this->rules;
    }
}

回答by Mr. Pyramid

much better way is to use nullablein Laravel 5.5 validations

更好的方法是nullable在 Laravel 5.5 验证中使用

Ref Docs

参考文档

The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values.

验证中的字段可能为空。这在验证可包含空值的字符串和整数等原语时特别有用。

class ImageRequest extends Request
{   
    /**
     * Rules array
     */
    protected $rules = [
        'title' => 'required|string|between:3,60',
        'alt'   => 'nullable|string|between:3,60',
        'image' => 'nullable|image|max:4000|dimensions:min_width=200,min_height=200',
    ];

    /**
     * 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 $this->rules;
    }
}

However I have used recently with image and it worked like charm for me. Give it a try!

然而,我最近使用了图像,它对我来说很有魅力。试一试!

回答by Marcin Nabia?ek

The simplest way in this case in the other way. By default have rules for update and if it's store add required like so:

在这种情况下最简单的方法是另一种方法。默认情况下有更新规则,如果它是商店添加需要像这样:

class ImageRequest extends Request
{   
    /**
     * Rules array
     */
    protected $rules = [
        'title' => 'required|string|between:3,60',
        'alt'   => 'sometimes|string|between:3,60',
        'image' => 'image|max:4000|dimensions:min_width=200,min_height=200',
    ];

    /**
     * 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()
    {
        $rules = $this->rules;

        if ($this->isMethod('POST')) {
           $rules['image'] = 'required|' . $rules['image']
        }

        return $rules;
    }
}