public function store(Request $request, User $user)
{
$role = Role::find($request->role);
$user = User::find($user->id);
$role->user()->attach($user);
}
Laravel 5.4 how to assign roles to user by form request?
i have a users list & here i put a option to assign role to each users, for that when click 'Add Role' link it will show this route
Route::get('admin/home/role/{user}', 'RoleController@create');
in create function my form code is...
<form method="post" action="{{ url('admin/home/role') }}">
{{ csrf_field() }}
<div class="form-group">
<select name="role" class="form-control" >
<option value="1"> Admin </option>
<option value="2"> Editor</option>
</select>
</div>
<button type="submit" class="btn btn-primary">
Add Role
</button>
</form>
to manage this form my POST route is...
Route::post('admin/home/role', 'RoleController@store');
now how to insert this form request data into role_user table? oh! i have already 3 table, users, roles & role_user.
User model relationship code is...
public function role()
{
return $this->belongsToMany(Role::class, 'role_user');
}
Role model relationship code is...
public function user()
{
return $this->belongsToMany(User::class, 'role_user');
}
my question is how to insert form request data into role_user table? i know one way that is...
public function store(Request $request, User $user)
{
$role = Role::find(1);
$user = User::find(19);
$role->user()->attach($user);
}
it works, but this is not dynamic. How to insert by form request? please help me. I searching about this topic tutorial but not found.
Please or to participate in this conversation.