【问题标题】:Laravel 4 : Authentication when having a many to many relationshipLaravel 4:具有多对多关系时的身份验证
【发布时间】:2014-10-09 12:01:38
【问题描述】:

我有一个用户、角色和角色用户表。在角色表中,我有一个用户和管理员值。现在我希望能够在用户角色为管理员时编辑用户。我不知道如何在 laravel 中访问 role_name == 'admin'。

当我使用它时它可以工作:

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

但我希望能够访问这个role_name == 'admin'

role_users 迁移

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';
   }
}

【问题讨论】:

  • 您的user 模型中是否定义了role 关系?
  • 这是一个多对多关系,所以它将user_id和role_id存储在一个名为role_users的表中。我使用 role_users 迁移编辑了我的问题。
  • 请同时包含用户模型文件。
  • 包括用户模型。
  • 所以你想看看用户是否有rolename=='admin'

标签: php authentication laravel laravel-4 many-to-many


【解决方案1】:

你应该可以做这样的事情:

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
}

编辑 刚刚意识到我脑子里放了个屁。更正了代码:-)

【讨论】:

    【解决方案2】:

    你可以在你的用户模型上添加一个检查这个的函数...

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

    然后您可以轻松地将它与...一起使用

    @if(Auth::user()->isAdmin())
    

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2014-01-25
      • 2013-09-11
      • 1970-01-01
      • 2020-12-26
      • 2013-11-14
      • 2019-03-23
      • 2013-09-29
      • 2021-12-20
      相关资源
      最近更新 更多