I want to create a random string with the length of 8 using Str::random() and then use validator to check whether the created string satisfied the conditions or not
Since the string is generated inside the function. I think the Request object is not required (also this question How to validate without request in Laravel strengthen the point) so I did go with
$random_str = Str::random(8);
$validator = Validator::make(['random_str' => $random_str], [
'random_str' => 'min:9',
]
if (!validator) {
Log::info('validation failed');
return [];
}
Since the $random_str length is 8, I expect the validator to fail but it didn’t. When I try the Request object, it works as expected.
$random_str = Str::random(8);
$request = new Request([
'random_str' => $random_str
]);
$validator = $request->validate([
'random_str' => 'min:9',
]
if (!validator) {
Log::info('validation failed');
return [];
}
>Solution :
when using Validator::make(), don’t forget to call fails() to check if the validation has failed.
Use this
$random_str = Str::random(8);
$validator = Validator::make(['random_str' => $random_str], [
'random_str' => 'min:9',
]);
if ($validator->fails()) {
Log::info('Validation failed');
return [];
}