我正在使用Spatie laravel-permissions软件包。创建角色时,我想为角色分配权限,但是返回错误:
参数1传递给 Spatie \ Permission \ Exceptions \ GuardDoesNotMatch :: create()必须属于 类型字符串,给定null,在 C:\ xampp \ htdocs \ blog \供应商\ spatie \ laravel-permission \ src \ Traits \ HasPermissions.php 在第505行
控制器
public function store(Request $request)
{
// Validate name and permissions field
$this->validate($request, [
'name' => 'required|unique:' . config('permission.table_names.roles') . '|max:10',
]
);
$name = $request['name'];
$role = new Role();
$role->name = $name;
$permissions = $request->permissions;
$role->save();
// Looping thru selected permissions
foreach ($permissions as $permission) {
$p = Permission::where('id', '=', $permission)->firstOrFail();
// Fetch the newly created role and assign permission
$role = Role::where('name', '=', $name)->first();
$role->givePermissionTo($p);
}
return redirect()->route('roles.index')
->with('flash_message', 'Role' . $role->name . ' added!');
}
刀片
<div class='col-lg-10 col-lg-offset-4'>
<h1><i class='fa fa-key'></i> Add Role</h1>
<hr>
<form action="{{action('RoleController@store')}}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group row" style="margin:5%;">
<label for="name" class="col-sm-2 col-form-label">Name *</label>
<input type="text" class="form-control col-sm-10" id="name" name="name"
placeholder="Enter your Role Name"/>
</div>
<h5><b>Assign Permissions</b></h5>
<div class="form-check">
@foreach ($permissions as $permission)
<input class="form-check-input" type="checkbox" name="permissions[]" value="{{ $permission->id }}">
<label class="form-check-label" for="defaultCheck1">
{{$permission->name}}
</label>
@endforeach
</div>
<div class="form-group row" style="margin:5%;">
<button type="submit" class="btn btn-primary col-sm-3 col-sm-offset-3">Add Role</button>
</div>
</form>
</div>
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
解决方案:
模型的$ guard_name与$ Request不同或为NULL,请确保两者都在同一个Guard'web'/'api'
中//解决方法:@VardanaBhanot在评论中
RoleController.php
public function store(Request $request)
{
// validate role 'name' and make sure that's unique within 'roles' table
// upon creating a role we want to make sure that it's not an empty role
// so permissions are required
$this->validate($request, [
'name' => 'required|unique:roles|max:10',
'permissions' => 'required'
]);
// create the role by given name and assign it to @var $role
$role = Role::create(['name' => $request['name']]);
// since we are using Validator to make sure "permissions" exists
// we can skip the "isset($request['permission'])" call.
foreach($request['permissions'] as $permission)
{
if($p = Permission::where('id', '=', $permission)->first())
{
$role->givePermissionTo($p);
}
}
}