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

SigalZ's avatar

Livewire complax validation on array

I have this livewire component with an array of inputs:

$this->weights = [
        [
            'weight' => '250g',
            'price' => ' ',
		    'selectedBag' => ''
        ],
        [
           'weight' => '1kg',
            'price' => ' ',
		    'selectedBag' => ''
        ]
];

protected function rules()
    {
        return [          
            'weights.*.price' => 'numeric'
        ];
    }

    protected function messages()
    {
        return [
            'weights.*.price.numeric'   =>  'The price must be numeric',          
        ];
    }

The selectedBag is required only if the price is not empty.

I see this in Laravel validation documentation, but I don't understand how to implement it with livewire:

$input = [
    'channels' => [
        [
            'type' => 'email',
            'address' => '[email protected]',
        ],
        [
            'type' => 'url',
            'address' => 'https://example.com',
        ],
    ],
];
$validator->sometimes('channels.*.address', 'email', function ($input, $item) {
    return $item->type === 'email';
});

I think I should do something like this, but I don't understand where should I add it?:

$validator->sometimes('weights.*.selectedBag', 'required', function ($input, $item) {
    return $item->price != ' ' && $item->price != 0;
});
0 likes
1 reply
ramonrietdijk's avatar

You can access the Validator instance when validating in order to add your custom requirements.

Laravel also has a required_with validation rule. Note that this will only check if a value is present so it won't check the zero in this case.

return [          
    'weights.*.price' => 'numeric',
    'weights.*.selectedBag' => 'required_with:weights.*.price'
];

Please or to participate in this conversation.