Validation rules required_if with other condition (Laravel 5.4)
When configuring validation logic in Laravel, chaining conditional rules like required_if with type checks can lead to confusing behavior if the syntax isn't precise. Consider a scenario where you are validating a request for a new record involving type_id and external_id. The goal is simple: ensure external_id is present only when type_id equals 3, but always ensure that whenever external_id is provided, it contains an integer value.
The problematic code often looks like this:
class StoreRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'type_id' => 'required|integer',
'external_id' => 'required_if:type_id,==,3|integer',
];
}
}
At first glance, the logic appears sound. The required_if directive correctly gates the presence of external_id based on the type_id. However, a common pitfall arises when type_id is set to anything other than 3 (for example, 1 or 2). In this state, required_if evaluates to false, meaning the field becomes optional. If you submit the form with an empty external_id, Laravel bypasses the "presence" check. Yet, if that empty string fails the subsequent integer cast during validation, you might encounter errors like "The external_id must be an integer."
This happens because of how Laravel's validator processes chained rules. When a field is optional, it still undergoes type casting for rules like integer. If the input is an empty string, the cast fails immediately, triggering the error even though the field was meant to be skipped entirely. The validator does not automatically skip non-type-checking rules just because a field is optional; it only skips the "required" check.
To fix this, you must ensure that the integer constraint is also conditional or handled differently depending on whether the field is present. There are two primary approaches in Laravel 5.4.
Approach 1: Conditional Casting via Logic
The cleanest solution in this version of Laravel is to separate the presence check from the type check, or to use a closure for dynamic validation logic if the rules become too complex for static strings. However, for simple cases, you can often rely on nullable combined with specific conditional rules, though this has trade-offs regarding how empty strings are handled versus nulls.
A more robust pattern that avoids the type-checking error on optional fields is to make the external_id nullable and conditionally require it:
'external_id' => 'nullable|integer|required_if:type_id,==,3',
Wait, this still has an issue. If type_id is not 3, the field is nullable. An empty string submitted for a nullable integer field will fail the integer rule because an empty string is not an integer. The validator expects either a valid integer or a null value.
The correct implementation requires acknowledging that if the field is optional and left blank, it must be treated as null, not an empty string. However, HTML forms naturally submit empty strings. To truly make this work without errors on empty inputs when the condition isn't met, you often need to ensure the input is actually null or use a closure:
public function rules()
{
return [
'type_id' => 'required|integer',
'external_id' => [
function ($input) {
if ($input['type_id'] == 3) {
return ['required', 'integer'];
} else {
// If not required, ensure it's either empty/null or an integer.
// But standard form submission sends empty strings for blanks.
// To avoid "must be integer" error on blanks, we rely on the fact that
// if it's not required, the validator skips type checks ONLY if the value is null.
// Since forms send "", we must handle this carefully.
return 'nullable|integer';
}
}
],
];
}
Actually, relying on closures adds complexity. A simpler, standard approach for Laravel 5.4 that avoids the "must be integer" error when the field is optional is to simply not apply the integer rule when the field is optional unless you handle the empty string conversion in your controller or view. But strictly speaking, if you want the validation rules to handle it purely:
You must accept that a blank field for an optional integer will fail a strict integer check unless you explicitly allow it to be null. The best practice here is often to remove the integer rule from the string when the condition is false, or use a closure as shown above to dynamically return the rule set.
If you strictly want to keep rules in a static array without closures and avoid the error, you must ensure the frontend sends null (which is hard with standard HTML forms) or you accept that the field will fail type validation if left blank when optional. The most pragmatic fix for the specific error described is to use a closure to dynamically define the rules based on the incoming type_id, ensuring the integer rule is skipped entirely when the field is not required.
This approach ensures that when type_id is 1 or 2, the validator sees no constraints on external_id other than it being nullable (handling empty strings gracefully), whereas when type_id is 3, it enforces both presence and integer type.