Kritim Yantra
Mar 27, 2025
Validations are crucial in web applications to ensure that user-submitted data is correct, secure, and follows business rules. Laravel provides a simple yet powerful way to validate incoming data.
In this guide, we’ll cover:
✅ Basic Form Request Validation
✅ Custom Validation Rules
✅ Real-Time Validation with Livewire (Optional)
✅ Error Handling & Displaying Messages
Let’s dive in!
Before processing user input, we must check:
Laravel makes this easy with built-in validation features.
validate()
in ControllersThe simplest way is to validate directly in a controller.
use Illuminate\Http\Request;
public function register(Request $request)
{
// Validate the request
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:8|confirmed',
]);
// If validation passes, create user
User::create($validated);
return redirect('/dashboard')->with('success', 'Registration successful!');
}
Rule | Meaning |
---|---|
required |
Field must not be empty |
string |
Must be a text value |
max:255 |
Maximum 255 characters |
email |
Must be a valid email |
unique:users |
Email must not exist in users table |
min:8 |
Minimum 8 characters |
confirmed |
Requires matching password_confirmation field |
❌ If validation fails, Laravel automatically redirects back with errors.
Laravel stores errors in the $errors
variable (available in Blade).
<form method="POST" action="/register">
@csrf
<!-- Name Field -->
<div>
<label>Name</label>
<input type="text" name="name" value="{{ old('name') }}">
@error('name')
<span style="color: red;">{{ $message }}</span>
@enderror
</div>
<!-- Email Field -->
<div>
<label>Email</label>
<input type="email" name="email" value="{{ old('email') }}">
@error('email')
<span style="color: red;">{{ $message }}</span>
@enderror
</div>
<!-- Password Field -->
<div>
<label>Password</label>
<input type="password" name="password">
@error('password')
<span style="color: red;">{{ $message }}</span>
@enderror
</div>
<!-- Confirm Password -->
<div>
<label>Confirm Password</label>
<input type="password" name="password_confirmation">
</div>
<button type="submit">Register</button>
</form>
✔ old('field')
repopulates form data after validation fails.
✔ @error('field')
displays validation errors.
Instead of cluttering controllers, Laravel allows dedicated validation classes.
php artisan make:request RegisterUserRequest
rules()
Methodpublic function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:8|confirmed',
];
}
public function register(RegisterUserRequest $request)
{
// Validation passed automatically!
User::create($request->validated());
return redirect('/dashboard');
}
✅ Benefits:
✔ Cleaner controllers
✔ Reusable validation logic
Sometimes, built-in rules aren’t enough. Let’s create a custom rule.
php artisan make:rule ForbiddenUsername
Now, edit app/Rules/ForbiddenUsername.php
:
public function passes($attribute, $value)
{
return strtolower($value) !== 'admin';
}
public function message()
{
return 'The :attribute cannot be "admin".';
}
use App\Rules\ForbiddenUsername;
$request->validate([
'username' => ['required', new ForbiddenUsername],
]);
For a smoother UX, validate fields as the user types using Laravel Livewire.
use Livewire\Component;
class RegisterForm extends Component
{
public $email;
public function updatedEmail()
{
$this->validateOnly('email', [
'email' => 'required|email|unique:users',
]);
}
public function render()
{
return view('livewire.register-form');
}
}
Now, errors appear instantly without page reload!
Rule | Example | Description |
---|---|---|
required |
'name' => 'required' |
Field must be filled |
email |
'email' => 'email' |
Must be a valid email |
min:8 |
'password' => 'min:8' |
Minimum 8 characters |
max:255 |
'title' => 'max:255' |
Maximum 255 chars |
confirmed |
'password' => 'confirmed' |
Needs password_confirmation |
unique:users |
'email' => 'unique:users' |
Must not exist in DB |
file |
`'photo' => 'file | max:2048'` |
date |
'dob' => 'date' |
Must be a valid date |
Laravel validations are easy yet powerful!
✔ Use $request->validate()
for quick checks.
✔ Form Request classes keep controllers clean.
✔ Custom rules handle unique business logic.
✔ Livewire enables real-time validation.
🚀 Now go ahead and secure your Laravel forms!
Transform from beginner to Laravel expert with our personalized Coaching Class starting June 11, 2025. Limited enrollment ensures focused attention.
1-hour personalized coaching
Build portfolio applications
Industry-standard techniques
Interview prep & job guidance
Complete your application to secure your spot
Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google