1

I am using multiple select in my form, facing problem with its form validation, i am using multiple select field name as array if i give same name for validation rule its work great, but keep giving validation error on selected options also. here is my html code and validation rule.

<select multiple="multiple" name="skills[]" class="form-control">

validation rule

'skills[]' => 'required'

if i use field name without [] or skills.* validation not working for this field, guide me where i am doing something wrong. I am using laravel 5.7 for my project.

4
  • 1
    You have to use it without [] Commented Jan 11, 2019 at 23:47
  • And hello btw :P studied at SAE together lol :D Commented Jan 12, 2019 at 0:59
  • @emotality yes i remember you Commented Jan 12, 2019 at 8:08
  • @devk i have to use without [] in validation rule? Commented Jan 12, 2019 at 8:09

1 Answer 1

4

If your select looks like this for example:

<div class="form-group row">
    <label for="skills" class="col-md-4 col-form-label text-md-right">Skills</label>
    <div class="col-md-6">
        <select multiple name="skills[]" id="skills" class="form-control{{ $errors->has('skills') ? ' is-invalid' : '' }}" required>
            <option value="ios">iOS</option>
            <option value="php">PHP</option>
            <option value="laravel">Laravel</option>
        </select>
        @if($errors->has('skills'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $errors->first('skills') }}</strong>
            </span>
        @endif
    </div>
</div>

Create a custom request:

$ php artisan make:request ExampleRequest

ExampleRequest validation would look like this:

public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'skills' => 'required|array',
    ];
}

Then just grab the validated data from your $request directly

public function submitForm(ExampleRequest $request)
{
    // at this point, validation already passed
    // if validation failed, you would be back at form with errors
    $skills = request('skills');
    // or
    $skills = $request->skills;

    dd($skills);
}

Custom requests are being validated first before even hitting your controller method.

Sign up to request clarification or add additional context in comments.

5 Comments

Why required needs form-control?
Yes created a new project with a new request, ran all scenarios and its working 100%. :) Show your whole validation maybe you’re doing something wrong?
Updated the answer. :)
yes its working fine, in my formbuilder for getting errors i was using field name with [] that's why it was now showing error. thanks for help
No problem, keep well! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.