我有一个users,roles和role_users表。在角色表中,我有一个用户和管理员值。现在,我希望能够在用户角色为admin时编辑用户。我不知道如何在laravel中访问role_name =='admin'。
当我使用它时它起作用:
@if(Auth::user()->user_username == 'Gilko')
但我希望能够访问此role_name == 'admin'
role_users migration
public function up()
{
Schema::create('role_users', function($table)
{
$table->increments('role_user_id');
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
});
Schema::table('role_users', function($table)
{
$table->foreign('role_id')
->references('role_id')->on('roles');
//->onDelete('cascade');
$table->foreign('user_id')
->references('user_id')->on('users');
//->onDelete('cascade');
});
}
用户模型:
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $hidden = ["password"];
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->user_password;
}
public function getReminderEmail()
{
return $this->email;
}
public function user()
{
return $this->hasMany('Checklist', 'user_id', 'user_id');
}
public function roles(){
return $this->belongsToMany('Role', 'role_users', 'user_id', 'role_id');
}
public function getRememberToken()
{
//return $this->remember_token;
}
public function setRememberToken($value)
{
//$this->remember_token = $value;
}
public function getRememberTokenName()
{
//return 'remember_token';
}
}
答案 0 :(得分:3)
你应该可以这样做:
if (Auth::user()->roles()->where('name', 'admin')->first())
如果没有结果, first
将返回null。
您还可以使用firstOrFail
:http://laravel.com/docs/eloquent
try (Auth::user()->roles()->where('name', 'admin')->firstOrFail()) {
// User has admin role
} catch (ModelNotFoundException $e) {
// User doesn't have admin role
}
编辑刚刚意识到我有一个大脑放屁。更正了代码: - )
答案 1 :(得分:2)
您可以在用户模型上添加一个检查此功能的功能......
public function isAdmin()
{
return (bool)$this->roles()->where('name', 'admin')->count();
}
然后你可以轻松地将它用于......
@if(Auth::user()->isAdmin())