Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tommasoKuhn's avatar

Validation with key variabile

A Request class for validations has this structure:

class MyRequest extends FormRequest{

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

Would it be possible to have the array key as a variable (type: string)? Example

public function rules(Post $post)
{
    $titleVariable = $this->createTitleFunction($post);

    return [
        'title-'.$titleVariable => 'required|unique:posts|max:255',
    
        'body' => 'required',
    ];
}

or dynamic title:

public function rules()
{

    return [
        'title-1' => 'required|unique:posts|max:255',
    ...
    'title-n'
        'body' => 'required',
    ];
}

is possible? Thank

PS: sorry for my english.

0 likes
1 reply
sujancse's avatar

You can do like

public function rules()
{
    return [
        'title.*' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

If your title contains like title[1], title[2] And the error message key will be title.1, title.2 etc.

Please or to participate in this conversation.