Could we help you? Please click the banners. We are young and desperately need the money
One of the most important aspects of building web applications is ensuring that user input is clean, safe, and valid. In Laravel, form validation is both powerful and beginner-friendly. This tutorial will guide you through the basics of Laravel validation and move into advanced techniques that help you write cleaner and more maintainable forms.
Without validation, your forms can quickly become a gateway for bugs, broken layouts, and even security issues. Laravel provides a wide range of built-in validation rules and an elegant syntax, so you can focus more on building features and less on debugging messy form submissions.
When handling forms in a controller, you can call the "validate()" method directly. For example, validating a simple registration form:
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:50',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:8|confirmed',
]);
// If validation passes, proceed with creating the user
User::create($validated);
}
This example checks that:
For cleaner controllers, Laravel allows moving validation rules into custom Form Request classes. This is useful as your rules grow more complex.
php artisan make:request StoreUserRequest
// In StoreUserRequest.php
public function rules()
{
return [
'name' => 'required|string|max:50',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:8|confirmed',
];
}
// In your Controller
public function store(StoreUserRequest $request)
{
User::create($request->validated());
}
This way, the controller remains clean, and validation logic is reusable.
Sometimes rules only apply under certain conditions. You can use the "sometimes()" method:
$request->validate([
'company' => 'nullable|string',
'company_id' => 'required_with:company|integer',
]);
Here, "company_id" is only required if a "company" value is present.
If built-in rules are not enough, you can create custom validation logic.
php artisan make:rule Uppercase
// In Uppercase.php
public function passes($attribute, $value)
{
return strtoupper($value) === $value;
}
public function message()
{
return 'The :attribute must be uppercase.';
}
// In controller or request
$request->validate([
'code' => ['required', new Uppercase],
]);
Laravel makes it easy to validate array inputs, such as multiple addresses or tags:
$request->validate([
'tags' => 'required|array|min:1',
'tags.*' => 'string|max:30',
]);
This ensures "tags" is an array with at least one item, and each item is a string of max 30 characters.
Mastering validation in Laravel helps you prevent bad data, improve security, and build cleaner forms. By starting with the basics and moving into advanced features like custom rules and array validation, you’ll quickly develop forms that are both user-friendly and robust.