所以这就是问题所在:
我创建了一个CRUD系统,以便管理员可以创建/读取/更新/删除用户。 问题是我无法在CRUD系统中为用户选择角色。真的很感激任何帮助!
我将指出我正在使用的3次迁移:user_role用户,角色和数据透视表。
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name', 40);
$table->string('description', 255);
});
Schema::create('user_role', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->integer('role_id');
});
这是我的用户模型:
public function roles(){
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}
这是我的角色模型:
public function users(){
return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id');
}
我在RoleTableSeeder中播放了一些角色,如下所示:
Role::create([
'id' => 1,
'name' => 'Admin',
'description' => 'Admin User.'
]);
Role::create([
'id' => 2,
'name' => 'Vendor',
'description' => 'Vendor User.'
]);
Role::create([
'id' => 3,
'name' => 'User',
'description' => 'Simple User.'
]);
这是创建用户的代码:
{!! Form::open(['route' => 'admin.users.allusers']) !!}
<div class="form-group">
{!! Form::label('Username', 'Username:') !!}
{!! Form::text('username',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('E-mail', 'E-mail:') !!}
{!! Form::text('email',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('Role', 'Role:') !!}
<select class="form-control" id="role" name="role">
<option value="Administrator">Administrator</option>
<option value="Vendor">Vendor</option>
<option value="User" selected="selected">User</option>
</select>
</div>
<div class="form-group">
{!! Form::submit('Create', ['class' => 'btn btn-primary']) !!}
<a href="{{ route('admin.users.allusers')}}" class="btn btn-primary">Back</a>
</div>
{!! Form::close() !!}
答案 0 :(得分:2)
创建用户后,您需要明确初始化角色关系。
$user = User::create(Request::all()); //user needs to be saved first so that ID is known
$role = Role::whereName(Request::input('role'))->first();
$user->roles()->attach($role);