🛡️ How Laravel Helps You Filter Bad Data
Stop Dirty Data: Laravel Validation Tips You Can’t Ignore
In any modern web application, validating user input is not just a best practice—it's essential. Whether you're building a small blog or a massive enterprise API, Laravel makes input validation elegant, powerful, and flexible.
✅ What is Request Validation?
Request validation is the process of ensuring that incoming data is in the expected format before processing it. Laravel provides a fluent, expressive interface for defining validation rules directly within your controllers, form requests, or even custom classes.
🚀 Why Validation is Important
Here are just a few reasons why validation is non-negotiable:
Security: Prevent malicious input like SQL injection or XSS attacks.
Data Integrity: Keep your database clean and consistent.
User Experience: Provide clear error messages when something goes wrong.
Reliability: Avoid processing incomplete or incorrect data.
🧠 Laravel Validation Strategies
Laravel gives us multiple ways to handle validation. Let’s explore each with examples and when to use them:
1. Inline Validation in Controllers (Quick & Simple)
Add validation logic directly inside the controller:
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
]);
// Continue with your logic...
}2. Form Request Validation (Recommended)
Use php artisan make:request StoreUserRequestclass StoreUserRequest extends FormRequest
{
public function rules(): array
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
];
}
public function authorize(): bool
{
return true; // add permission logic if needed
}
}In your controller:
public function store(StoreUserRequest $request)
{
$validated = $request->validated();
}💬 Customize the Error Message
add in StoreUserRequest
public function messages()
{
return [
'name.required' => 'Please provide your name.',
'name.min' => 'Your name must be at least :min characters.',
'email.required' => 'We need your email address.',
'email.email' => 'This is not a valid email format.',
'email.unique' => 'This email is already registered.',
'password.required' => 'A password is mandatory.',
'password.min' => 'Password must be at least :min characters.',
'password.confirmed' => 'Passwords do not match.',
];
}🧪 How to Add Custom Validation Rule
Create a custom rule called AlphaSpace that ensures a field only contains letters (a–z) and spaces. We'll apply this rule to a user's full name field.
🧩 Step 1: Generate the Custom Rule
php artisan make:rule AlphaSpaceThis will create a file at:
app/Rules/AlphaSpace.php🧩 Step 2: Define the Rule Logic
Open AlphaSpace.php and update it like this:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class AlphaSpace implements Rule
{
public function passes($attribute, $value): bool
{
// Allow only letters and spaces
return preg_match('/^[a-zA-Z\s]+$/', $value);
}
public function message(): string
{
return 'The :attribute may only contain letters and spaces.';
}
}🧩 Step 3: Use the Rule in a Form Request
In RegisterUserRequest.php
use App\Rules\AlphaSpace;
public function rules(): array
{
return [
'full_name' => ['required', new AlphaSpace],
'email' => 'required|email|unique:users,email',
'password' => 'required|string|min:8|confirmed',
];
}🧩 Step 4: Use the Request in Controller
use App\Http\Requests\RegisterUserRequest;
public function register(RegisterUserRequest $request)
{
$validated = $request->validated();
// You can now safely use $validated['full_name']
}🧪 Example Inputs
✅ Benefits of Custom Rules
Encapsulates logic in a reusable class
Makes your validation cleaner and modular
Great for domain-specific validation (e.g., policy number, PAN, GSTIN, etc.)
✅ Benefits of Using Laravel Validation
🚫 Prevents bad data from entering your system
💡 Clear and readable syntax
📦 Reusable with Form Requests
🔧 Customizable with custom rules
🔄 Automatically returns JSON errors for APIs
🧘 Wrapping Up
In this article, we covered how to implement and organize request validation effectively in Laravel. You learned:
✅ Inline Validation
A quick and simple method perfect for small tasks, one-off features, or prototyping.📄 Form Request Validation
A clean and reusable approach ideal for larger applications, keeping your controllers slim and focused.🧩 Custom Validation Rules
A powerful way to enforce domain-specific or business-critical logic that goes beyond built-in Laravel rules.



