Hoda Kh
Hoda Kh

Reputation: 355

Laravel validation rule to force user to fill at least one input out of three

I have a form in my blade with 3 inputs. User must at least fill one of the inputs, I mean each input is required if the others are empty. I don't know how to write my validation rules in Laravel controller. The inputs:

                       <div class="mt-3">
                            <x-label for="telegram" value="__('Telegram')"/>
                            <x-input
                                type="text" name="telegram"
                                class="mt-1 block w-full"
                                autofocus/>
                        </div>

                        <div class="mt-3">
                            <x-label for="whatsapp" value="__('Whatsapp')"/>
                            <x-input
                                type="text" name="whatsapp"
                                class="mt-1 block w-full"
                                autofocus/>
                        </div>

                        <div class="mt-3">
                            <x-label for="discord" value="__('Discord')"/>
                            <x-input 
                                  type="text" name="discord"
                                  class="mt-1 block w-full"
                                  autofocus/>
                        </div>

Upvotes: 0

Views: 224

Answers (1)

Luciano
Luciano

Reputation: 2196

In your controller, you can validate your request and use required_without_all rule.

required_without_all:foo,bar,...
The field under validation must be present and not empty only when all of the other specified fields are empty or not present.
$validated = $request->validate([
        'telegram' => 'required_without_all:whatsapp,discord',
        'whatsapp' => 'required_without_all:telegram,discord',
        'discord' => 'required_without_all:telegram,whatsapp',
]);

Upvotes: 3

Related Questions