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

murtaza1904's avatar

How to validate data if condition is true in Laravel Livewire

public function rules()
    {
            return array_merge(
              (new FirstRequest())->rules(),
		      (new SecondRequest())->rules(),
			);
	}

This is how I can use multiple request class in livewire but there is a problem with that. This will validate all Request Classes at once. I want to make it check if the checkbox is checked then validate that data. For example if form one checkbox is checked that validate First Request class. same for second form. And If both form checkbox are checked validate both

0 likes
3 replies
ItsClassified's avatar

Pretty sure the 'public function rules()' gets checked when you are validating.

For that reason you can isntead of returning the array right away, create an array, check if the checkbox is checked and then add the rule to the array, to the same for the second one. When you're done you return the array and that is the amount of rules that will be validated!

murtaza1904's avatar
public function rules()
    {
        return array_merge(
                (new PatientRequest())->rules(),
                (new ContactRequest())->rules(),
                (new ChoiceRequest())->rules(),
                (new EmployerRequest())->rules(),
                (new StatsRequest())->rules(),
                (new MiscRequest())->rules(),
                (new GuardianRequest())->rules(),
                (new PrimaryInsuranceRequest())->rules(),
                (new SecondaryInsuranceRequest())->rules(),
                (new TertiaryInsuranceRequest())->rules(),
            );
    }

I am using like this, but it validates all . I want to validate data if checkbox is checked

ItsClassified's avatar

@murtaza1904

public function rules()
    {
		
		$rules = [];

		if(checkbox == checked) {
			// add the new (PatientRequest())->rules() to the $rules array
        }

		//etc

		return $rules;
      
    }

Any reason why something like this wouldnt work?

Please or to participate in this conversation.