Conditional Rules

Conditional Rules and Array Validation

An ebook needs a download link and no shipping weight, a sale price is checked only when sent, and a book has a list of authors. rules() gained these entries, and messages() gained 'authors.*.name.required' => 'Author #:position needs a name.':

Conditional and array rules in StoreProductRequest::rules()PHP
'download_url' => ['required_if:format,ebook', 'nullable', 'url'],
'weight_grams' => Rule::when($this->input('format') === 'ebook',
    ['prohibited'], ['required', 'integer', 'min:1']),
'sale_price' => ['sometimes', 'decimal:0,2', 'lt:price'],
'authors' => ['required', 'array', 'min:1'],
'authors.*.name' => ['required', 'string', 'max:80'],
'authors.*.role' => ['required', Rule::in(['author', 'editor', 'translator'])],

ebook.json posts an ebook priced 47.5 with a sale_price of 49, a weight_grams and no download link, whose second author is {"role": "illustrator"}:

Output of 72
$ curl -s $A -H "$H" -H "$J" -H 'Content-Type: application/json' -d @ebook.json \
    $B/products | errs
download_url: The download url field is required when format is ebook.
weight_grams: The weight grams field is prohibited.
sale_price: The sale price field must be less than 47.5.
authors.1.name: Author #2 needs a name.
authors.1.role: The selected authors.1.role is invalid.

Errors are keyed by path, as @error('authors.1.name') and old() expect for an input named authors[1][name]; :position counts from 1, :index from 0. A paperback without sale_price skipped its rules (sometimes) but had to send weight_grams. Relatives include required_with, exclude_if and Rule::requiredIf(fn () => ...).