Search code examples
phplaravelselectroles

Laravel - How to get select value and pass it to RegisterController create()


I have the following problem, how can I get the value of a select on my register.blade.php?

When a user register he should be able to select a role, each role has an id and once he clicks on the submit button the role id should be assigned to his rol_id on users table.

But I don't know how to get the value of the selected id once I use the create method on RegisterController.

Part of the register.blade.php that has the select:

<div class="form-group row">
    <label for="rol_id" class="col-md-4 col-form-label text-md-right">Rol:</label>
    <div class="col-md-6">
        <select class="form-select" name="rol_id" id="rol_id">
            <option value="2">User</option>
            <option value="3">Editor</option>
            <option value="1">Admin</option>
        </select>
    </div>
</div>

What should I put on the rol_id? This is the create method where I should assign the id of the role selected:

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\Models\User
 */
protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'rol_id' =>
    ]);

    return $user;
}

If you need more methods/classes I'll provide it.

UPDATE: Also Im facing another problem, once a User is created the rol_id gets assigned, but I have another table called role_user where there is the user id and the rol id, there is no much sense on having that pivot table if users can only have one role right?

Thanks!


Solution

  • As the user @dazed-and-confused shared with you in the question's comments, you must use 'rol_id' => $data['rol_id']. That is your fix/solution.

    Now, I am going to expand a little bit more on why:

    Any form you send to any URL (form's action), it is going to send any input, textarea and select. But these elements MUST have a name attribute, in your case it would be name="rol_id" (<select class="form-select" name="rol_id" id="rol_id">).

    So, to read any of these elements in your controller, you have to use $request->input('NAME_OF_ELEMENT'), for example: $request->input('email').

    You can also send other data types directly like strings, booleans, numbers (integers, float, etc), but you have mostly to do an AJAX call (using axios, for example).