Laravel provides us with built-in functions to perform many validation tasks very easily. One such is the use of helper functions in Laravel to verify if a string is null in Laravel. Here we can use both. ways, either the PHP comparison operators or Laravel Helper functions.
Consider the code snippets below on the various ways to verify if a string is null in Laravel.
Verify Null Strings in Laravel
The is_null
function
$check_string = "";
if (is_null($check_string)) {
// check_string is null
} else {
// check_string is not null
}
The is_null
function checks a string and returns true if it is empty or null. It is a simple and easy-to-use function that reduces excess code usage for multiple validations.
The empty
function
$check_string = "";
if (empty($check_string)) {
// check_string is null
} else {
// check_string is not null
}
The empty
function also works in a similar way to the is_null
function in Laravel. It returns true for an empty string variable and false otherwise, as shown above.
In addition to using the helper functions as explained above, we can also define validation rules as stated below.
public function rules()
{
return [
'age' => 'integer',
'title' => 'nullable|string|max:50'
];
}
To verify a title, we can add the attributes to it as shown above. This verifies if the entered title is a string with maximum 50 characters and allows nullable entries for it.