Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

twg_'s avatar
Level 6

Writing new user plus roles to the database.

I have a simple form for creating a new user which includes a checkbox list of all the available roles. I'm trying to figure out how to iterate through the roles once the user has been created and then save the roles to my roles table.

public function store(Request $request)
{
    $rules = array(
        'name'      =>  'required',
        'email'     =>  'required|email|unique:users',
        'password'  =>  'required|min:10'
    );

    $validator = Validator::make(Input::all(), $rules);

    if($validator->fails())
    {
        return Redirect::to('admin/users/create')
            ->withInput();
    }else{
        $user = new User;
        $user->name = Input::get('name');
        $user->email = Input::get('email');
        $user->password = Hash::make(Input::get('password');
        $user->save();

        // How to get the roles
        // Then iterate over them to save them to my user_roles table.

        Session::flash('success', 'Your new user has been added.');
        return Redirect::to('admin/users');
    }
}

Checkboxes look like

@foreach($roles as $role)
    <div class="checkbox">
        <label>
            <input type="checkbox" name="roles" id="role_{{ $role->name }}" value="{{ $role->id }}" /> {{ $role->display_name }}
        </label>
    </div>
@endforeach 
0 likes
4 replies
willvincent's avatar
Level 54

First things first, your input name will need to be roles[] so that it can accept multiple values.

At that point, roles will be an array of role IDs, so you should be able to simply do:

$user->roles()->sync(Input::get('roles'));
1 like
jlrdw's avatar

A checkbox for a role, I'd have a different form for user versus an admin to fill out what is to stop a user from checking that they are an admin. Unless I misunderstood something.

twg_'s avatar
Level 6

@willvincent & @jekinney thanks for the quick response. I was trying to make it a lot more complicated than I needed to.

@jlrdw A user won't get access to change their role. Only admins see this section.

Please or to participate in this conversation.