Anvil
Anvil - The mobile companion for Laravel Forge. Available now. Download for iOS

Reuse Validation Logic with Rule::when()

  • Laravel
  • Validation

In Laravel, you can simplify conditional validation logic using Rule::when(). This allows you to apply rules dynamically based on certain conditions, making your validation logic cleaner and more readable. Unlike sometimes(), which can become messy with complex conditions, Rule::when() offers a more straightforward approach to conditionally applying validation rules.

Use conditional logic inside rule definitions:

1use Illuminate\Validation\Rule;
2 
3Rule::when($user->isAdmin(), ['required', 'email']);