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

schnabs's avatar

Building a User Roles editor in Laravel

I'm trying to make an editor page for what is probably best described as a User/Role editor. (A page where an admin can assign Users to a Role)

There is a User model and a Role model which have a many-to-many relationship. I am fine with setting up the pivot table and adding the relationship to the models. I also have functioning User and Role restfull controllers. I'm a little hung up on how I should create this editor page in a 'Laravel' like way.

(A) If I was using vanilla PHP I would probably make a post request including the role_id and user_ids[] array and build all the logic to update the DB from there.

(B) If I was using Vue/JS/AJAX I could create a restfull controller 'UserRoleController' representing each row in the pivot table and make a rest call for each add/remove action. ( would prefer to keep this serverside only if possible for now, maybe need a little ajax for the list of users which can be added but that's it)

So currently my feeling is to take my restfull RoleController and add a method called something like 'syncUsers($request)' and create an addition link to this method in routes.php and make it a POST or PUT/PATCH at '../role/syncusers/'? (I would put this above the resourceful route in case someone creates a role called syncusers.) Then it would be easy to pull the IDs and use $role->users()->sync(...) to persist.

Is this the right way to go about this or is there a more 'laravel like' clean way?

Thanks! let me know if further clarification is needed

0 likes
2 replies
bobbybouwmann's avatar
Level 88

I would simply create a sync function in your RolesController for it. I would even post to a url where the role id already exists

// routes.php
Route::post('roles/{id}/sync', 'RolesController@sync');

// RolesController

public function sync(Request $request, $id)
{
    $role = Role::findOrFail($id);
    
    $this->syncUsers($request, $role);

    // Redirect the user to some page
    return redirect()->route('roles.index');
}

protected function syncUsers(Request $request, Role $role)
{   
    // We do this extra check because if you use checkboxes you might not post 
    // any data if no checkbox are checked
    $users = $request->has('users') ? $request->get('users') : [];

    $role->users()->sync($users):
}
schnabs's avatar

That makes a lot of sense, thanks for your reply :)

Please or to participate in this conversation.