This controller method checks user input for name, email, and age. It ensures name and email are present and valid, email is unique, and age is optional but if given must be a number 13 or older. If validation passes, it returns a success message with the valid data.
Laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:50',
'email' => 'required|email|unique:users,email',
'age' => 'nullable|integer|min:13',
]);
// Normally save user here
return response()->json(['message' => 'User data is valid', 'data' => $validated]);
}
}
OutputSuccess
Important Notes
Validation helps keep your database clean and reliable.
Laravel automatically redirects back with errors if validation fails in web routes.
Always validate data coming from users or external sources.
Summary
Validation checks data before saving to keep it correct.
Use Laravel's validate() method with rules to enforce data formats.
This prevents bad data and helps your app work smoothly.
Practice
(1/5)
1. Why is validation important in Laravel when handling user input?
easy
A. It ensures data is correct before saving to the database.
B. It speeds up the application by skipping checks.
C. It automatically fixes errors in user input.
D. It hides user input from the database.
Solution
Step 1: Understand the role of validation
Validation checks user input to make sure it meets rules before saving.
Step 2: Identify the benefit of validation
This prevents wrong or harmful data from entering the database, keeping data clean.
Final Answer:
It ensures data is correct before saving to the database. -> Option A
Quick Check:
Validation = Data correctness [OK]
Hint: Validation checks data correctness before saving [OK]
Common Mistakes:
Thinking validation fixes data automatically
Believing validation speeds up app by skipping checks
Confusing validation with data hiding
2. Which is the correct way to validate a required email field in a Laravel controller?
easy
A. $request->validate(['email' => 'required|email']);
B. $request->validate(['email' => 'email,required']);
C. $request->validate(['email' => 'required_email']);
D. $request->validate(['email' => 'require|email']);
Solution
Step 1: Check Laravel validation syntax
Laravel uses pipe-separated rules like 'required|email' for validation.
Step 2: Identify correct rule order and spelling
$request->validate(['email' => 'required|email']); uses correct rules and spelling: 'required|email'. Others have wrong order or invalid rules.
Final Answer:
$request->validate(['email' => 'required|email']); -> Option A