所以我正在使用Laravel 5.2和委托包来管理角色/权限
我正在构建一个函数,它应该向'users'表添加一个用户,同时向'role_user'表添加一个关系。我正在从multi_select传递一个数组,然后将其附加到用户。
它将用户完美地添加到'users'表中,但没有在'role_user'表中添加关系。我希望有人能帮我找出问题所在。
有问题的表单部分:
{!! Form::select('roles[]', $roles, null, ['multiple' => 'multiple', 'class' => 'select-width-100 form-control roles']) !!}
My StoreUser function
public function StoreUser(Request $request)
{
$input = Request::all();
$user = New User;
$user->name = $input['username'];
$user->email = $input['email'];
$user->password = Hash::make($input['password']);
$roles = $input['roles'];
foreach ($roles as $role)
{
$role_id = Role::where('name', $role)->first();
$user->roles()->attach($role_id);
}
$user->save();
return redirect('/settings/users');
}
下面是我的User.php模型
<?php
namespace App;
use ZizacoEntrustTraitsEntrustUserTrait;
use IlluminateFoundationAuthUser as Authenticatable;
class User extends Authenticatable
{
use EntrustUserTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
我设法修复了它。我应该寻找'id'而不是'name',所以这个:
foreach ($roles as $role)
{
$role_id = Role::where('name', $role)->first();
$user->roles()->attach($role_id);
}
应该是这样的:
foreach ($roles as $role)
{
$role_id = Role::where('id', $role)->first();
$user->roles()->attach($role_id);
}