labeeb's avatar

How to make all validations fail and show message in laravel

In a controller I am using two validation like this:

public function update(Request $request){

if( $request->hasFile('img1') ){

    $request->validate(
        [   
            'img1'=>'image'
        ]
    );

    
}


if( $request->hasFile('img2') ){

    $request->validate(
        [   
            'img2'=>'image'
        ]
    );

    
}

}

Now if I upload incorrect file types for both img1 & img2 Only the first validation is checked and laravel redirects user to the original form page. This way message for only first validation is displayed. Even though second file type was also incorrect. I want to make sure all validate methods are checked are executed before I get redirected to the page I came from i.e., the page containing form.

Also I can't put validate method for file in one if statement as img1 and img2 might not be present at the same time. Because user might just want to upload one file.

0 likes
2 replies
Sanctuary's avatar

Why not just make a $validationRules array and then do $request->validate($validationRules)? e.g.:

$validationRules = [
    'some_field' => 'required|min:2|max:100',
    'some_other_field' => 'required|accepted',
];

if ($request->hasFile('img1')) {
    $validationRules['img1'] = 'image';
}

if ($request->hasFile('img2')) {
    $validationRules['img2'] = 'image';
}

$request->validate($validationRules);

But do you even need to do it conditionally? I don't think it'd fail if you just did

$request->validate([
    'img1' => 'image',
    'img2' => 'image',
]);

But someone correct me if I'm wrong; I haven't tested it out.

As a side note, if your validation code starts to get long and you're still storing it in your controller, you may wanna look into created form request classes to keep your controllers clean (link).

Please or to participate in this conversation.