In this in-depth tutorial, you will learn how to implement advanced validation rules in Laravel for secure forms. We’ll cover everything from custom rules, closures, and conditional validation to form requests and security best practices. By the end, you’ll have the skills to build robust, safe, and professional-grade Laravel applications.
When working with user input, validation is one of the most critical steps in securing your Laravel application. Beginners often rely only on simple built-in rules like required, email, or min, but Laravel’s validation system is much more powerful. It allows you to create custom rules, use closures, validate arrays, apply conditional logic, and even build reusable form request classes.
In this article, we’ll take a professional deep dive into Laravel’s advanced validation rules and techniques. Each step will be backed with examples and clear explanations so you can confidently apply them in your real-world projects.
Getting Started with Laravel Validation
Basic Validation Refresher
Laravel provides the validate() method and the Validator facade to apply validation rules. Here’s a quick refresher:
// In a controller method
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
'age' => 'nullable|integer|min:18'
]);
// If validation passes, continue
User::create($validated);
}
This basic validation is helpful, but not enough for complex or security-critical applications. Let’s go deeper.
You can generate a custom validation rule using Artisan:
php artisan make:rule StrongPassword
This creates app/Rules/StrongPassword.php where you can define your logic:
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class StrongPassword implements Rule
{
public function passes($attribute, $value)
{
return preg_match('/^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$/', $value);
}
public function message()
{
return 'The :attribute must be at least 8 characters long and include one uppercase letter, one number, and one special character.';
}
}
Now use it in your controller:
use App\Rules\StrongPassword;
$request->validate([
'password' => ['required', new StrongPassword]
]);
Using Closure-Based Custom Rules
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'code' => [
'required',
function ($attribute, $value, $fail) {
if ($value !== 'SECRET123') {
$fail($attribute.' is invalid.');
}
},
],
]);
Conditional Validation
Sometimes rules depend on other fields. Laravel offers several techniques.
This ensures only images under 2MB with minimum dimensions of 100×100 are accepted.
Localization of Validation Messages
You can customize error messages in resources/lang/en/validation.php. For example:
'custom' => [
'username' => [
'regex' => 'Username may only contain letters, numbers, and underscores.',
],
],
Best Practices for Secure Validation
Always validate both client-side and server-side.
Use custom rules for domain-specific security needs.
Never trust hidden inputs; validate all incoming data.
Prefer Form Requests for reusable, clean code.
Use bail to reduce unnecessary processing.
Keep error messages user-friendly but not overly revealing.
Comparison Table: Validation Methods
The table below summarizes different ways to apply validation in Laravel:
Method
Use Case
Example
Inline Validation
Simple one-off validations
$request->validate([...])
Validator Facade
More control and conditional logic
Validator::make(...)
Form Request
Reusable, structured validation
RegisterUserRequest
Minimal but production-ready example
Let's create a minimal but complete Laravel example that demonstrates advanced validation rules in one flow. This example will include:
A form for user registration.
Controller method with advanced validation rules.
A custom rule (StrongPassword).
Form Request class for clean validation.
Example of conditional validation.
1. Create the Route
// routes/web.php
use App\Http\Controllers\RegisterController;
Route::get('/register', [RegisterController::class, 'create']);
Route::post('/register', [RegisterController::class, 'store']);
2. Create the Controller
// app/Http/Controllers/RegisterController.php
namespace App\Http\Controllers;
use App\Http\Requests\RegisterUserRequest;
use App\Models\User;
class RegisterController extends Controller
{
public function create()
{
return view('register');
}
public function store(RegisterUserRequest $request)
{
// Validation already handled by RegisterUserRequest
User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
'phone' => $request->phone,
]);
return redirect('/register')->with('success', 'User registered successfully!');
}
}
3. Create the Custom Rule
php artisan make:rule StrongPassword
// app/Rules/StrongPassword.php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class StrongPassword implements Rule
{
public function passes($attribute, $value)
{
return preg_match('/^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$/', $value);
}
public function message()
{
return 'The :attribute must contain at least 8 characters, one uppercase letter, one number, and one special character.';
}
}
4. Create the Form Request
php artisan make:request RegisterUserRequest
// app/Http/Requests/RegisterUserRequest.php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Rules\StrongPassword;
class RegisterUserRequest extends FormRequest
{
public function authorize()
{
return true; // allow all for demo
}
public function rules()
{
return [
'name' => 'required|string|max:100',
'email' => 'required|email|unique:users,email',
'password' => ['required', new StrongPassword, 'confirmed'],
'phone' => 'nullable|regex:/^[0-9]{10}$/',
'company' => 'required_if:is_employed,true',
'is_employed' => 'boolean',
];
}
public function messages()
{
return [
'company.required_if' => 'Company name is required when employed.',
'phone.regex' => 'Phone number must be exactly 10 digits.',
];
}
}
Laravel’s validation system goes far beyond the basics. With advanced rules, custom logic, conditional validation, and Form Requests, you can build secure, scalable, and user-friendly applications. The key takeaway is: never compromise on validation. Treat every piece of user input as potentially harmful, and leverage Laravel’s powerful tools to protect your application.
Now, practice applying these techniques in your projects. Start small by adding a custom rule, then move toward full-fledged Form Requests with complex validation logic. Over time, you’ll master secure form handling in Laravel.
This article is a comprehensive tutorial on using the Prohibited Validation Rules in Laravel. You will learn how to apply prohibited, prohibited_if, and prohibited_unless with clear explanations, real-life scenarios, and code examples. This guide is perfect for developers who want to master advanced validation techniques in Laravel applications.
This detailed tutorial explores request validation in Laravel controllers. You’ll learn multiple techniques—basic controller validation, using form request classes, custom rules, conditional validation, error handling, localization, and best practices. With practical examples, code snippets, and structured explanations, this article is designed for beginners to advance learner.
This guide teaches you how to deploy Laravel applications to production servers. From preparing your environment and configuring Nginx or Apache, to database migrations, caching, performance optimization, CI/CD pipelines, and security practices—this article covers everything step by step.It’s suitable for both beginners and advanced developers who want to ship stable, secure & scalable app.
This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy
These cookies are essential for the website to function properly.
These cookies help us understand how visitors interact with the website.
These cookies are used to deliver personalized advertisements.