Laravel validation rules if field empty another field required

Stefan Izdrail

Founder & Senior Architect · 2026-06-29

Laravel Company
Title: Simplifying Laravel Form Validation for Complex Conditions Introduction Laravel's form validation is an essential feature that helps ensure data integrity in web applications. In this post, we'll explore how to create a specific set of rules where one field is required only when another is empty. This can be useful for scenarios like user profile updates with hidden image fields. Let's dive into the implementation details using Laravel 5.3 and JavaScript code snippets. Setting Up Form Inputs First, let's create an HTML form with relevant inputs for your desired functionality. In this case, you have a hidden input field for displaying the old image value:
<input type="hidden" class="form-control" name="old_image" value="{{ $player->>image_filename }}" id="oldImage">
And another input field for the new image upload:
<input type="file" class="form-control" name="new_image" id="newImage" />
When a user removes their current image, you can use JavaScript to clear the hidden input value:
document.getElementById('oldImage').value = '';
Laravel Form Validation Rules Now we need to define validation rules that will ensure proper data handling. You've tried using `required_without` and `required_if`, but they didn't show error messages when the image was missing. The reason is that, by default, Laravel doesn't trigger errors for empty values in hidden fields since they don't contain user-provided input. To overcome this issue, you need to create a custom validation rule that will check for both fields' presence and display an appropriate error message if the new image isn't provided: Custom Validation Rule Class First, create a new PHP file called 'CustomImageValidator.php':

errors()->add('old_image', 'You need to provide a new image or select the existing one.');
        }
    }
}
Now, let's update your model validation rules:
<input type="hidden" class="form-control" name="old_image" value="{{ $player->>image_filename }}" id="oldImage">
...
    public function rules() {
        return [
          'first_name' => 'required|max:50',
          'last_name' => 'required|max:50',
          'birthday' => 'required',
          'image' => ['image', new CustomImageValidator],
        ];
    }
Conclusion In this comprehensive blog post, we've covered how to implement Laravel form validation rules in your application to address a specific set of conditions. You've learned the importance of custom validation classes and how they can help with complex scenarios like validating an image field when another is empty or hidden. Remember to use appropriate backlinks to https://laravelcompany.com for further reference on Laravel development and best practices.