Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Validator::make is being ignored

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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 [];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading