0
0
Laravelframework~8 mins

Custom validation rules in Laravel - Performance & Optimization

Choose your learning style9 modes available
Performance: Custom validation rules
MEDIUM IMPACT
Custom validation rules affect server-side request processing time and can indirectly impact user experience by delaying response time.
Validating user input with custom rules in Laravel
Laravel
Validator::extend('check_simple', function ($attribute, $value, $parameters, $validator) {
    // Simple in-memory check or cached data
    $allowedValues = cache()->remember('allowed_values', 3600, fn() => DB::table('small_table')->pluck('field')->toArray());
    return in_array($value, $allowedValues);
});
Uses cached data to avoid repeated heavy queries, reducing validation time significantly.
📈 Performance GainReduces validation time to under 10 ms, improving server response speed
Validating user input with custom rules in Laravel
Laravel
Validator::extend('check_complex', function ($attribute, $value, $parameters, $validator) {
    // Heavy database queries inside validation
    $result = DB::table('large_table')->where('field', $value)->get();
    return $result->count() > 0;
});
Running heavy database queries inside validation blocks request processing and increases server response time.
📉 Performance CostBlocks server response for 100+ ms per request depending on query complexity
Performance Comparison
PatternServer ProcessingNetwork DelayClient Render DelayVerdict
Heavy DB queries in validationHigh CPU and I/O usageIncreased due to slower responseDelayed due to late data arrival[X] Bad
Cached data in validationLow CPU usage, fast lookupMinimal network delayFaster client rendering[OK] Good
Rendering Pipeline
Custom validation rules run on the server before the response is sent, affecting the time until the browser receives data to render.
Server Processing
Network Transfer
Browser Rendering
⚠️ BottleneckServer Processing due to complex validation logic
Core Web Vital Affected
INP
Custom validation rules affect server-side request processing time and can indirectly impact user experience by delaying response time.
Optimization Tips
1Avoid heavy database queries inside custom validation rules.
2Use caching to store data needed for validation to speed up checks.
3Keep validation logic simple to reduce server processing time and improve user experience.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a common performance issue with custom validation rules in Laravel?
ACaching validation results
BUsing simple PHP functions for validation
CRunning heavy database queries inside validation logic
DValidating only on client side
DevTools: Network and Performance panels
How to check: Use Network panel to measure server response time; use Performance panel to see time spent waiting for server data before rendering.
What to look for: Look for long server response times indicating slow validation; shorter times indicate efficient validation.