简体   繁体   中英

Laravel: Validate field only when the value changed

Some form fields in my laravel 5.5 application have validation rules that run against a remote API and take quite some time. I would thus only want to run these expensive checks when the field value changes (is different from the value currently stored in the model).

Is there something that implements this already, eg as a rule similar to sometimes ?

I would image it like this: only_changed|expensive_validation|expensive_validation2 . The latter rules would only be executed when the field value has changed.

Assuming you are using a custom Request class, the rules() method expects an associative array to be returned before it applies the validation.

You can build your array of rules dynamically using the request contents before applying the validation like so:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    $validation_array = [
        'name'     => 'required|string|max:255',
    ];

    if ($this->my_field === $some_condition) {
        $validation_array = array_merge($validation_array. [
            'my_field' => "required|expensive_validation|expensive_validation2"
        ]);
    }

    return $validation_array;
}

Note: I haven't run this yet but the principle should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM