我正在使用Laravel 5.2和Zizaco/entrust
,我的问题是:
在下面的示例中,如何保存用户的角色?
**注册表格**,在开箱即用表格的基础上添加了Role
项目。
<form id="register" class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
{!! csrf_field() !!}
<fieldset class="form-group">
<label class="col-md-4 form-control-label">Role</label>
<div class="col-md-6">
<label class="c-input c-radio">
<input id="role1" name="role" type="radio" value="1">
<span class="c-indicator"></span>
red team
</label>
<label class="c-input c-radio">
<input id="role2" name="role" type="radio" value="2">
<span class="c-indicator"></span>
blue team
</label>
</div>
</fieldset>
<fieldset class="form-group{{ $errors->has('name') ? ' has-danger' : '' }}">
<label class="col-md-4 form-control-label">username</label>
<div class="col-md-6">
<input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}">
@if ($errors->has('name'))
<span class="help-block"><strong>{{ $errors->first('name') }}</strong></span>
@endif
</div>
</fieldset>
<fieldset class="form-group{{ $errors->has('email') ? ' has-danger' : '' }}">
<label class="col-md-4 form-control-label">email</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
@if ($errors->has('email'))
<span class="help-block"><strong>{{ $errors->first('email') }}</strong></span>
@endif
</div>
</fieldset>
<fieldset class="form-group{{ $errors->has('password') ? ' has-danger' : '' }}">
<label class="col-md-4 form-control-label">password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password">
@if ($errors->has('password'))
<span class="help-block"><strong>{{ $errors->first('password') }}</strong></span>
@endif
</div>
</fieldset>
<fieldset class="form-group{{ $errors->has('password_confirmation') ? ' has-danger' : '' }}">
<label class="col-md-4 form-control-label">password confirmation</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation">
@if ($errors->has('password_confirmation'))
<span class="help-block"><strong>{{ $errors->first('password_confirmation') }}</strong></span>
@endif
</div>
</fieldset>
<fieldset class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">submit</button>
</div>
</fieldset>
</form>
AuthController开箱即用。
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
我可以制作一个RolesController并编写一个attachRole()函数,因此,我可以手动将角色附加到用户。像这样:
public function attachRole()
{
$user = User::where('name', '=', 'foo')->first();
$user->roles()->attach(2);
return "attachRole done";
}
现在,我想保存从注册表中收到的角色,但不想通过上面的attachRole()附加角色
如何修改AuthController中的create
函数?
您可以使用Laravel中的授权功能来完成此操作,https://laravel.com/docs/5.2/authorization.
示例代码:
$gate->before(function ($user, $ability) {
if ($user->isSuperAdmin()) {
return true;
}
});