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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制