🎯 Learning Objectives
- Create Laravel forms with CSRF protection
- Handle form submissions in controllers
- Implement server-side validation
- Display validation errors
- Use old() helper to repopulate forms
🔐 CSRF Protection
Security First! Laravel protects against Cross-Site Request Forgery (CSRF) attacks. Every form MUST include @csrf directive.
Basic Form with CSRF:
<!-- resources/views/contact.blade.php -->
<form action="/contact" method="POST">
@csrf
<label>Name:</label>
<input type="text" name="name">
<label>Email:</label>
<input type="email" name="email">
<label>Message:</label>
<textarea name="message"></textarea>
<button type="submit">Send</button>
</form>
📝 Handling Form Submission
Route Definition:
<?php
// routes/web.php
use App\Http\Controllers\ContactController;
Route::get('/contact', [ContactController::class, 'show']);
Route::post('/contact', [ContactController::class, 'submit']);
?>
Controller with Validation:
<?php
// app/Http/Controllers/ContactController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ContactController extends Controller
{
public function show()
{
return view('contact');
}
public function submit(Request $request)
{
// Validate form data
$validated = $request->validate([
'name' => 'required|min:3|max:50',
'email' => 'required|email',
'message' => 'required|min:10|max:500',
]);
// Process the data (save to database, send email, etc.)
// For now, just redirect with success message
return redirect('/contact')->with('success', 'Message sent successfully!');
}
}
?>
✅ Validation Rules
| Rule | Description | Example |
|---|---|---|
| required | Field must not be empty | 'name' => 'required' |
| Must be valid email format | 'email' => 'email' | |
| min:n | Minimum length/value | 'password' => 'min:8' |
| max:n | Maximum length/value | 'name' => 'max:50' |
| numeric | Must be a number | 'age' => 'numeric' |
| alpha | Only letters (A-Z, a-z) | 'name' => 'alpha' |
| alpha_num | Letters and numbers only | 'username' => 'alpha_num' |
| confirmed | Must match _confirmation field | 'password' => 'confirmed' |
| unique:table | Value must be unique in table | 'email' => 'unique:users' |
| in:val1,val2 | Value must be in list | 'role' => 'in:admin,user' |
🚨 Displaying Validation Errors
Method 1: Display All Errors
<!-- Show all errors at top of form -->
@if($errors->any())
<div style="background: #f8d7da; color: #721c24; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
<strong>Please fix the following errors:</strong>
<ul style="margin: 10px 0 0 20px;">
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
Method 2: Display Error Per Field
<label>Name:</label>
<input type="text" name="name" value="{{ old('name') }}">
@error('name')
<span style="color: red; font-size: 0.9em;">{{ $message }}</span>
@enderror
<label>Email:</label>
<input type="email" name="email" value="{{ old('email') }}">
@error('email')
<span style="color: red; font-size: 0.9em;">{{ $message }}</span>
@enderror
🔄 Repopulating Forms with old()
old() helper retrieves previously submitted values, so users don't have to re-type everything when validation fails.
<input type="text" name="name" value="{{ old('name') }}">
<input type="email" name="email" value="{{ old('email') }}">
<textarea name="message">{{ old('message') }}</textarea>
<!-- For select dropdown -->
<select name="country">
<option value="nigeria" {{ old('country') == 'nigeria' ? 'selected' : '' }}>Nigeria</option>
<option value="ghana" {{ old('country') == 'ghana' ? 'selected' : '' }}>Ghana</option>
</select>
<!-- For checkboxes -->
<input type="checkbox" name="agree" {{ old('agree') ? 'checked' : '' }}> I agree
💻 Complete Registration Form Example
Route:
<?php
// routes/web.php
use App\Http\Controllers\RegisterController;
Route::get('/register', [RegisterController::class, 'show']);
Route::post('/register', [RegisterController::class, 'store']);
?>
Controller:
<?php
// app/Http/Controllers/RegisterController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
public function show()
{
return view('register');
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|min:3|max:50|alpha',
'email' => 'required|email|unique:users',
'phone' => 'required|numeric|min:10',
'password' => 'required|min:8|confirmed',
'age' => 'required|numeric|min:18|max:100',
'gender' => 'required|in:male,female',
'agree' => 'required',
]);
// Save to database (we'll learn this next week)
// For now, just show success
return redirect('/register')->with('success', 'Registration successful!');
}
}
?>
View (resources/views/register.blade.php):
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<style>
body { font-family: Arial; max-width: 600px; margin: 50px auto; padding: 20px; }
h1 { color: #fcb69f; text-align: center; }
.form-group { margin-bottom: 20px; }
label { display: block; margin-bottom: 5px; font-weight: bold; color: #333; }
input, select, textarea {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;
}
.error { color: #dc3545; font-size: 0.9em; margin-top: 5px; }
.success {
background: #d4edda;
color: #155724;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.error-box {
background: #f8d7da;
color: #721c24;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
button {
background: #fcb69f;
color: white;
padding: 12px 30px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
width: 100%;
}
button:hover { background: #fa9882; }
</style>
</head>
<body>
<h1>Student Registration</h1>
@if(session('success'))
<div class="success">
{{ session('success') }}
</div>
@endif
@if($errors->any())
<div class="error-box">
<strong>Please fix the following errors:</strong>
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="/register" method="POST">
@csrf
<div class="form-group">
<label>Full Name *</label>
<input type="text" name="name" value="{{ old('name') }}" placeholder="Ahmad Ibrahim">
@error('name')
<div class="error">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label>Email Address *</label>
<input type="email" name="email" value="{{ old('email') }}" placeholder="ahmad@example.com">
@error('email')
<div class="error">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label>Phone Number *</label>
<input type="text" name="phone" value="{{ old('phone') }}" placeholder="08012345678">
@error('phone')
<div class="error">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label>Password *</label>
<input type="password" name="password" placeholder="Minimum 8 characters">
@error('password')
<div class="error">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label>Confirm Password *</label>
<input type="password" name="password_confirmation" placeholder="Re-type password">
</div>
<div class="form-group">
<label>Age *</label>
<input type="number" name="age" value="{{ old('age') }}" placeholder="18">
@error('age')
<div class="error">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label>Gender *</label>
<select name="gender">
<option value="">Select Gender</option>
<option value="male" {{ old('gender') == 'male' ? 'selected' : '' }}>Male</option>
<option value="female" {{ old('gender') == 'female' ? 'selected' : '' }}>Female</option>
</select>
@error('gender')
<div class="error">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label>
<input type="checkbox" name="agree" {{ old('agree') ? 'checked' : '' }}>
I agree to the terms and conditions *
</label>
@error('agree')
<div class="error">{{ $message }}</div>
@enderror
</div>
<button type="submit">Register</button>
</form>
</body>
</html>
📋 Custom Validation Messages
<?php
$validated = $request->validate([
'name' => 'required|min:3',
'email' => 'required|email',
], [
'name.required' => 'Please enter your name.',
'name.min' => 'Name must be at least 3 characters.',
'email.required' => 'Email address is required.',
'email.email' => 'Please enter a valid email address.',
]);
?>
🎯 Method Spoofing (PUT/DELETE)
HTML forms only support GET and POST. For PUT/PATCH/DELETE, use @method directive.
<!-- Update form (PUT) -->
<form action="/students/{{ $id }}" method="POST">
@csrf
@method('PUT')
<!-- form fields -->
<button type="submit">Update</button>
</form>
<!-- Delete form -->
<form action="/students/{{ $id }}" method="POST">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
✏️ Practice Exercises
- Create a login form with email and password validation
- Build a contact form with name, email, subject, and message
- Create a product form with name, price (numeric), and description
- Add custom error messages to your forms
- Implement a profile update form with PUT method
- Create a form with dropdown, checkbox, and radio button validation
✅ Today's Deliverable
- ✓ Understand CSRF protection with @csrf
- ✓ Validate form data with multiple rules
- ✓ Display errors with @error directive
- ✓ Repopulate forms using old() helper
- ✓ Complete registration form with all validations
- ✓ Handle success messages with session flash