Undefined array key - Laravel/Fortify Register

Viewed 1310

Simply its a register page in Laravel .. User have to check the checkbox if its teacher if not is student.

Thus I tried to do with value 1 teacher 0 student but I dont know how to get this value in controller .

Also tried below code ( 'role_id' => $input['role_id'], ) when checked it returns "on" on database but non-checked it throws error

Undefined array key "role_id"

Register view..

<div class="form-group form-check">
   <input type="checkbox" class="form-check-input" id="role_id" name="role_id" value="0" 
   <label class="form-check-label" for="exampleCheck1">Teacher</label>
</div>

Fortify Controller..

/**
 * Validate and create a newly registered user.
 *
 * @param  array  $input
 * @return \App\Models\User
 */
public function create(array $input)
{
    Validator::make($input, [
        'name' => ['required', 'string', 'max:255'],
        'email' => [
            'required',
            'string',
            'email',
            'max:255',
            Rule::unique(User::class),
        ],
        'password' => $this->passwordRules(),
    ])->validate();

    return User::create([
        'name' => $input['name'],
        'email' => $input['email'],
        'password' => Hash::make($input['password']),
        'role_id' =>  $input['role_id'],
    ]);
}

}

1 Answers

Close /> input checkbox

<div class="form-group form-check">
   <input type="checkbox" class="form-check-input" id="role_id" name="role_id" value="1"/>
   <label class="form-check-label" for="exampleCheck1">Teacher</label>
</div>

and in controller

return User::create([
        'name' => $input['name'],
        'email' => $input['email'],
        'password' => Hash::make($input['password']),
        'role_id' =>  $input['role_id']??0,
    ]);
Related