mardi 10 octobre 2017

Laravel 5.5 conditional form request validation rule on update

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.

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 unique validation 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?

Apply required only for new images.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire