One of my latest Laravel tips on Twitter, discussing Laravel validators for checking the existence of fields, gained high momentum, and developers found it helpful. So here I am writing a blog post discussing the validators mentioned in the tip and other ones that Twitter friends suggested to me.
Laravel has a Validation engine with a rich set of validators. Today, I discuss validators that are specialized to validate the existence of a field or its value.
Namely, these fields:
- Required
- Present
- Filled
- Nullable
- Sometimes
Required Validator
The required
validator ensures that the field, coming in a request, is presently filled with data. For instance, in this validation example:
public function rules()
{
return [
'id' => 'required|...',
// other validations
];
}
The required
validator ensures that the id
field is present in the list of fields submitted to the Backend Endpoint and that it has a value and not empty.
Check the official document on Required Validator.
Present Validator
The present
validator ensures that the field, coming in a request, is present without necessarily filling with data. For instance, in this validation example:
public function rules()
{
return [
// other validations
'age' => 'present|...',
];
}
The present
validator ensures that the age
field is present, although it might be empty and has no value.
Check the official document on Present Validator.
Filled Validator
The filled
validator ensures that the field, coming in a request, is filled with data, only when it is present in the request. For instance, in this validation example:
public function rules()
{
return [
// other validations
'age' => 'filled|...',
];
}
The filled
validator ensures that the age
field is filled with data only when it's present in the request.
Check the official document on Filled Validator.
Nullable Validator
The nullable
validator ensures that if the field coming in the request is null, empty, or has no data inside it, then the rest of the validations won't run for this specific field. For instance, in this validation:
public function rules()
{
return [
// other validations
'phone' => 'nullable|numeric',
];
}
The nullable
validator ensures that the phone
field, if null or empty in the current request, won't execute the rest of the validation requirements. In this case, the phone should be of a numeric nature.
Check the official document on Nullable Validator.
Sometimes Validator
The sometimes
validator ensures that if the field coming in the request is present, then apply the rest of the validation for this field. For instance, in this validation:
public function rules()
{
return [
// other validations
'email' => 'sometimes|required|email']
];
}
The sometimes
validator ensures that the email
field, if present in the current request, then the email is validated against being required and that it holds a valid email address.
Check the official document on Sometimes Validator.
Until the next blog post! Cheers 🍻
Top comments (0)