0
0
Laravelframework~30 mins

Conditional validation in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Laravel Conditional Validation
📖 Scenario: You are building a simple Laravel form to register users. The form asks for a username, email, and password. You want to add validation rules that change depending on the user's input.For example, if the user provides an email, the username is optional. But if the email is empty, the username must be provided.
🎯 Goal: Create a Laravel controller method that validates the form data using conditional validation rules. The validation should require username only if email is not present, and require email only if username is not present. The password is always required.
📋 What You'll Learn
Create a Laravel controller method named register.
Use the validate method on the $request object.
Add conditional validation rules for username and email using required_without.
Always require password.
Return a success message if validation passes.
💡 Why This Matters
🌍 Real World
Conditional validation is common in forms where some fields depend on others. For example, users may provide either a username or an email to register.
💼 Career
Understanding Laravel validation helps backend developers ensure data integrity and provide good user feedback in web applications.
Progress0 / 4 steps
1
Create the register method and get form data
Create a public method called register in your controller that accepts a Request $request parameter.
Laravel
Need a hint?

Remember to use public function register(Request $request) inside the controller class.

2
Add the validation rules with conditional requirements
Inside the register method, use $request->validate() with an array of rules. Add 'username' => 'required_without:email', 'email' => 'required_without:username|email', and 'password' => 'required'.
Laravel
Need a hint?

Use the required_without rule to make fields required only if the other is missing.

3
Add a success response after validation
After the $request->validate() call, return a JSON response with ['message' => 'Registration successful'] and HTTP status 200.
Laravel
Need a hint?

Use return response()->json([...], 200); to send a success message.

4
Complete the controller with namespace and imports
Ensure the controller file starts with namespace App\Http\Controllers; and imports Illuminate\Http\Request. The full controller class should be named UserController and include the register method with validation and response.
Laravel
Need a hint?

Make sure the file has the correct namespace, imports, and class structure.