Amine
Amine

Reputation: 941

How to fix checkbox not returning values in Laravel

I am trying to adapt the default registration form in Laravel to my database custom users table; I have a checkbox that isn't returning values, and even though it's selected it doesn't return a value. The validator alerts me that the checkbox field is required after submitting even though I selected it.

This is the checkbox:

<!--checkbox-->
<div class="form-group row">
    <label for="usertype" class="col-md-4 col-form-label text-md-right">Type Utilisateur</label>
    <div class="col-md-6">
        <input type="checkbox" name="check[]" value="normal"/> Normal
        <input type="checkbox" name="check[]" value="admin"/> Admin
        <input type="checkbox" name="check[]" value="super"/> Super
        @if ($errors->has('usertype'))
            <span class="help-block">
                <strong>{{ $errors->first('usertype') }}</strong>
            </span>
        @endif
    </div>
</div> 

Edit: Validator

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'telephone' => ['required', 'numeric'],
            'usertype' => ['required', 'string'],
        ]);
    }

Note: I removed usertype from Validation but the registration wouldn't go on the register page would refresh and no error appears or any alerts

Upvotes: 1

Views: 1062

Answers (2)

daenerysTarg
daenerysTarg

Reputation: 352

Within your input elements, instead of name="check[]" change it to name="usertype[]".

Upvotes: 2

1000Nettles
1000Nettles

Reputation: 2334

You are currently submitting the value of the checkbox as check to Laravel, not name:

name="check[]"

You can adjust the validator to the following:

protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'telephone' => ['required', 'numeric'],
            'check' => ['accepted'],
        ]);
    }

For more information, check this out: https://laravel.com/docs/5.2/validation#rule-accepted. You should be using accepted for validating checkboxes if you want it them to be required.

After the validation is complete in your controller action, ensure that you're not just returning the validator. The validator will throw an exception if there's an issue, so you can just place any code you want run after the validation call.

Upvotes: 0

Related Questions