
10 Laravel Validation Techniques You Won’t Find in Tutorials
Table of Contents
- 1. Validating Against a Custom Rule Object With Dependencies
- 2. Validate Only If Another Field Is Present with sometimes + required_with
- 3. Using exclude_if to Dynamically Skip Validation
- 4. Custom Validation Inline with Closures
- 5. Validate Unique Only on Create, Not Update
- 6. Array Input Validation with Keys and Wildcards
- 7. Date Must Be After Field with Custom Message
- 8. Conditionally Required Using required_if With Multiple Conditions
- 9. Regex with Named Groups for Readability
- 10. Validation After Pre-processing Data
- Final Thoughts
Laravel's validation system is powerful and easy to use. You've probably seen the usual required|string|max:255
, but there’s a lot more under the hood that rarely gets talked about.
Let’s explore 10 advanced Laravel validation techniques that can level up your form handling game.
1. Validating Against a Custom Rule Object With Dependencies
You can inject services into custom rule objects – great for database checks or external API calls.
// app/Rules/ValidCompanyDomain.php
use Illuminate\Contracts\Validation\Rule;
class ValidCompanyDomain implements Rule
{
protected $domainService;
public function __construct(DomainService $domainService)
{
$this->domainService = $domainService;
}
public function passes($attribute, $value)
{
return $this->domainService->isAllowed($value);
}
public function message()
{
return 'The domain is not allowed.';
}
}
Register in AppServiceProvider
using a service container bind if needed.
sometimes
+ required_with
2. Validate Only If Another Field Is Present with Perfect for optional but interdependent fields.
$request->validate([
'phone' => 'sometimes|required_with:country_code|numeric',
'country_code' => 'nullable|string|max:5',
]);
exclude_if
to Dynamically Skip Validation
3. Using Hide a field from validation if a condition is met.
$request->validate([
'discount' => 'exclude_if:is_free,true|required|numeric|min:1',
]);
If is_free
is true
, the discount
field is ignored completely.
4. Custom Validation Inline with Closures
Useful for quick inline logic in controllers.
$request->validate([
'username' => [
'required',
function ($attribute, $value, $fail) {
if (str_contains($value, 'admin')) {
$fail('Username cannot contain "admin".');
}
},
],
]);
5. Validate Unique Only on Create, Not Update
Avoid unique constraint failures on the same record during update.
Rule::unique('users')->ignore($user->id)
$request->validate([
'email' => ['required', 'email', Rule::unique('users')->ignore($user->id)],
]);
6. Array Input Validation with Keys and Wildcards
When validating dynamic form arrays:
$request->validate([
'products.*.id' => 'required|integer|exists:products,id',
'products.*.quantity' => 'required|integer|min:1',
]);
Each item in the products
array must pass the validation.
7. Date Must Be After Field with Custom Message
Compare dates between fields elegantly.
$request->validate([
'start_date' => 'required|date',
'end_date' => 'required|date|after:start_date',
], [
'end_date.after' => 'The end date must be after the start date.',
]);
required_if
With Multiple Conditions
8. Conditionally Required Using More control over when a field is required.
$request->validate([
'delivery_date' => 'required_if:delivery,true|required_if:pickup,false|date',
]);
Or use custom logic:
Validator::make($data, [
'delivery_date' => [
'required_if:delivery,true',
function ($attribute, $value, $fail) use ($data) {
if (!$data['pickup'] && !$value) {
$fail('Delivery date is required if not picking up.');
}
},
]
]);
9. Regex with Named Groups for Readability
Improves maintainability of complex regex.
$request->validate([
'slug' => [
'required',
'regex:/^(?P<slug>[a-z0-9]+(?:-[a-z0-9]+)*)$/'
]
]);
Tip: Laravel doesn’t support named groups directly in the error messages, but it helps in testing and logging.
10. Validation After Pre-processing Data
Laravel allows you to sanitize or transform inputs before validation.
public function prepareForValidation()
{
$this->merge([
'username' => strtolower($this->username),
]);
}
Add this to your FormRequest
class to standardize data before validation rules are applied.
Final Thoughts
Laravel validation is deceptively deep. While most tutorials stick to the surface, these advanced techniques allow you to build more flexible and powerful validations that adapt to your business logic.
Have a favorite validation trick not listed here? Let’s discuss in the comments.
Comments (0)
What are your thoughts on "10 Laravel Validation Techniques You Won’t Find in Tutorials"?
You need to create an account to comment on this post.
Related articles
