Bird
Raised Fist0
Laravelframework~8 mins

Custom validation rules in Laravel - Performance & Optimization

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of creating a custom validation rule in Laravel?
easy
A. To define your own logic for validating data beyond built-in rules
B. To change the database schema automatically
C. To create new database tables
D. To generate HTML forms automatically

Solution

  1. Step 1: Understand Laravel validation rules

    Laravel provides built-in rules but sometimes you need to check data in a way not covered by them.
  2. Step 2: Purpose of custom validation rules

    Custom rules let you write your own logic to validate data exactly as you want.
  3. Final Answer:

    To define your own logic for validating data beyond built-in rules -> Option A
  4. Quick Check:

    Custom validation = custom logic [OK]
Hint: Custom rules check data your way, not Laravel's default [OK]
Common Mistakes:
  • Thinking custom rules change database structure
  • Confusing validation with form generation
  • Assuming custom rules create tables
2. Which method must you implement in a Laravel custom validation rule class to check if the data passes validation?
easy
A. check
B. message
C. validate
D. passes

Solution

  1. Step 1: Recall custom rule methods

    Laravel custom validation rules require two methods: passes and message.
  2. Step 2: Identify method for validation logic

    The passes method contains the logic to decide if the data is valid or not.
  3. Final Answer:

    passes -> Option D
  4. Quick Check:

    passes() checks data validity [OK]
Hint: passes() returns true/false for validation [OK]
Common Mistakes:
  • Using message() to check data validity
  • Assuming validate() or check() are required methods
  • Confusing method names
3. Given this custom rule class snippet, what will $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.';
    }
}
medium
A. true
B. Throws an error
C. false
D. null

Solution

  1. Step 1: Understand the passes method logic

    The method returns true if the value is 18 or more, false otherwise.
  2. Step 2: Evaluate passes with value 17

    Since 17 is less than 18, the method returns false.
  3. Final Answer:

    false -> Option C
  4. Quick Check:

    17 < 18 means passes() = false [OK]
Hint: Check condition in passes() with given value [OK]
Common Mistakes:
  • Assuming 17 passes as adult
  • Thinking passes() throws error for numbers
  • Confusing message() with passes()
4. What is wrong with this custom validation rule class?
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.';
    }
}
medium
A. message method should return a boolean
B. Missing semicolon after return statement in passes method
C. passes method should accept only one parameter
D. Class must extend a base validation class

Solution

  1. Step 1: Check syntax in passes method

    The return statement lacks a semicolon at the end, causing a syntax error.
  2. Step 2: Verify other method signatures

    message() correctly returns a string, passes() correctly has two parameters, and implementing the interface is enough.
  3. Final Answer:

    Missing semicolon after return statement in passes method -> Option B
  4. Quick Check:

    Missing semicolon = syntax error [OK]
Hint: Look for missing semicolons in PHP code [OK]
Common Mistakes:
  • Thinking message() must return boolean
  • Assuming passes() takes one parameter
  • Believing class must extend base class
5. You want to create a custom validation rule that checks if a string contains only vowels. Which approach correctly implements the passes method?
hard
A. return preg_match('/^[aeiouAEIOU]+$/', $value) === 1;
B. return strlen($value) > 0 && ctype_alpha($value);
C. return strpos($value, 'aeiou') !== false;
D. return $value == strtolower($value);

Solution

  1. Step 1: Understand the requirement

    The string must contain only vowels (a, e, i, o, u) in any case.
  2. Step 2: Analyze each option

    return preg_match('/^[aeiouAEIOU]+$/', $value) === 1; uses regex to check if the string contains only vowels from start to end. return strlen($value) > 0 && ctype_alpha($value); checks only letters but not vowels. return strpos($value, 'aeiou') !== false; checks if 'aeiou' substring exists, which is incorrect. return $value == strtolower($value); checks if string is lowercase, unrelated to vowels.
  3. Final Answer:

    return preg_match('/^[aeiouAEIOU]+$/', $value) === 1; -> Option A
  4. Quick Check:

    Regex matching only vowels = correct passes() [OK]
Hint: Use regex to match only vowels in string [OK]
Common Mistakes:
  • Using ctype_alpha without vowel check
  • Checking substring instead of full string
  • Confusing case check with vowel check
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard