skip to Main Content

I have a select box with 2 options. There are "child" options in both these options. So, if Option 1 is selected, one text field (Option1child) shows up and if Option 2 is selected 2 more checkbox fields (group) (Option2child1, Option2child2) shows up.

All of these fields are required.

So with Option1 selected and if user submits without entering Option1child, Laravel sends a "required" error.

If Option2 is selected and no child options checked, it shows the required error here too.

I am doing this in Vue + Laravel.

The problem is, when I select Option1 and submit, it shows the error, and when I select Option2 again and submit, I get another set of errors + the old error in the form.errors array. What I want to do is reset the errors array when we change the Option and submit. I can do this in Vue with

form.errors = {};

But how can we reset this in Laravel which seems to be validating again.

Validation in Laravel is done something like this:

 attr = $request->validate([
        'sendto' => 'required',
        'to' => 'required_if:sendto,==,Option1',
        'groups' => 'required_if:sendto,==,Option2|required_without:batches|nullable',
        'batches' => 'required_if:sendto,==,Option2|required_without:groups|nullable'
 ]);

I hope I am clear. Thank you for your help.

2

Answers


  1. Chosen as BEST ANSWER

    It seems required_if and required_without cannot be used together. I found a fix by doing this so it no longer shows the old errors and I also get child options required error in both cases.

    To recap, I have a select option with 2 options. If Option1 is selected, there is a child option which is required. If Option2 is selected there are 4 options of which at least 1 is required. The code that worked for me is:

        $validator = Validator::make($request->all(), [
            'newsletter' => 'required',
            'sendto' => 'required',
            'to' => 'required_if:sendto,==,Option1',
            'groups' => 'sometimes',
        ]);
    
        $validator->sometimes(array('groups', 'batches', 'gender', 'countries'), 'required_if:sendto,==,Option2', function ($input) {
            return ($input->groups == [] && $input->batches == [] && $input->gender == []  && $input->countries == []);
        });
    
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator->errors());
        }
    

    I hope it helps someone. I have had hard time trying to find a fix on the internet.

    If anyone has a better code, I will be happy to implement it.


  2. Laravel validation will handle the data in request every time you send the request, I thought that happened in your vue component you should debug data sent to your Laravel controller and be sure the data be correct from your vue component side.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search