drba1172 2014-08-15 18:04
浏览 49
已采纳

Laravel 4:具有多对多关系时的身份验证

I have a users, roles and role_users table. In the roles table I have a user and admin value. Now I want to be able to edit users when the role of a user is admin. I don't know how to access the role_name == 'admin' in laravel.

When I use this it works :

 @if(Auth::user()->user_username == 'Gilko')

But I want to be able to access this 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');
        });
    }

User model :

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';
   }
}
  • 写回答

2条回答 默认 最新

  • douye2488 2014-08-15 18:31
    关注

    You can add a function which checks for this on your user model...

    public function isAdmin()
    {
        return (bool)$this->roles()->where('name', 'admin')->count();
    }
    

    And then you can easily use it with...

    @if(Auth::user()->isAdmin())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要