Laravel: Apply validation rules only if the field is present
July 23, 2022 ‐ 1 min read
Validation rules in Laravel allow you to require fields and apply other validation rules. But in some cases you want to only validate the fields that are present in a request. For example, in an API that supports partial updates of a resource; PATCH requests in REST API's more specifically.
In such cases you can add the sometimes
rule to the validator rule list. This makes sure that the other validation rules are only applied if the field is present in the request.
For example:
<?php
public function rules()
{
return [
'name' => 'sometimes|required|max:255',
];
}
The combination of sometimes
and required
seems odd at first hand but is valid. The required
rule makes sure that the field
cannot be null
, the sometimes
rule allows the field to be kept out of the request.