Laravel8 - Validation Required if Another Field is Empty

  9455 views   1 year ago Laravel

In this article, I will share with you how to implement validation required if another field is empty.

we all know laravel provide a very large validation rule in by-default and it's make our work very easy. here i share one of the most common and most useful validation rule validation required if another field is empty.

in this example we have two fields one is 'primary_contact' and the second is 'secondary_contact'. if the user does not fill the 'primary_contact' then the 'secondary_contact' field make required for user.

we will use the "required_without" laravel validation rule for this.

Example :

public function store(Request $request)
{
 	$request->validate([
	  	"primary_contact" =>"required",
	  	"secondary_contact" =>"required_without:primary_contact"
 	]);

  	dd("Done!");
}

i hope it will be help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]