Performance: Custom validation rules
Custom validation rules affect server-side request processing time and can indirectly impact user experience by delaying response time.
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); });
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; });
| Pattern | Server Processing | Network Delay | Client Render Delay | Verdict |
|---|---|---|---|---|
| Heavy DB queries in validation | High CPU and I/O usage | Increased due to slower response | Delayed due to late data arrival | [X] Bad |
| Cached data in validation | Low CPU usage, fast lookup | Minimal network delay | Faster client rendering | [OK] Good |
passes and message.passes method contains the logic to decide if the data is valid or not.$rule->passes('age', 17) return?class AdultRule implements \Illuminate\Contracts\Validation\Rule {
public function passes($attribute, $value) {
return $value >= 18;
}
public function message() {
return 'You must be an adult.';
}
}class EvenNumberRule implements \Illuminate\Contracts\Validation\Rule {
public function passes($attribute, $value) {
return $value % 2 == 0
}
public function message() {
return 'The number must be even.';
}
}passes method?Pass the test and this pattern moves unknown