doucan4815
2018-02-02 15:49
浏览 905
已采纳

Laravel _如何将查询注入Auth :: user()

I'm making a blog with laravel. When I look into user authentication, I have a few issues here. I have 2 tables, one is users: id, name, ... the other is role: user_id, privilege .. I need to check whether a user is admin or not, I will need a function like isAdmin() or a $isAdmin attribute. This is my function placed in the app/providers/AuthServiceProvider.php:

private static $isAdmin;

public static function isAdmin() {
    if (isset(self::$isAdmin)) {
        return self::$isAdmin;
    }
    $user_privilege = DB::table('role')
        ->select('privilege')
        ->where([
            ['privilege', '=', 'admin'],
            ['user_id', '=', Auth::user()->id],
        ])
        ->get()
        ->first();
    self::$isAdmin = isset($user_privilege->privilege);
    return self::$isAdmin;
}

This code works fine, but this will require two queries to the database to check the user's admin rights. So I wanted to find a way to inject a query into Auth :: user () so that only one query would retrieve all the stuff I wanted. I'm a beginner with laravel. Can you help me?

图片转代码服务由CSDN问答提供 功能建议

我正在制作一个带有laravel的博客。 当我查看用户身份验证时,我在这里遇到了一些问题。 我有2个表,一个是用户:id,name,...另一个是role:user_id,privilege ..我需要检查用户是否是admin,我需要一个像 isAdmin()这样的函数 $ isAdmin 属性。 这是我的功能放在 app / providers / AuthServiceProvider.php 中:

  private static $ isAdmin; 
 
public static function isAdmin()  {
 if(isset(self :: $ isAdmin)){
 return self :: $ isAdmin; 
} 
 $ user_privilege = DB :: table('role')
  - > select('privilege  ')
  - > where([
 ['privilege','=','admin'],
 ['user_id','=',Auth :: user() - > id],\  n])
  - > get()
  - > first(); 
 self :: $ isAdmin = isset($ user_privilege-> privilege); 
 return self :: $ isAdmin; 
}  
   
 
 

此代码工作正常,但这需要对数据库进行两次查询以检查用户的管理员权限。 所以我想找到一种方法将查询注入Auth :: user(),这样只有一个查询可以检索我想要的所有东西。 我是laravel的初学者。 你能帮助我吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • doushi3803 2018-02-02 15:59
    最佳回答

    I assume that user can have only one role. You can create isAdmin() method in the User model:

    public function isAdmin()
    {
        return auth()->user()->role->privilege === 'admin';
    }
    

    Define the relationship if you didn't do that yet:

    public function role()
    {
        return $this->hasOne(Role::class);
    }
    

    Then use it with auth()->user()->isAdmin().

    If a user can have many roles:

    public function isAdmin()
    {
        auth()->user()->loadMissing('roles');
        return auth()->user()->roles->contains('admin');
    }
    

    And the relationship:

    public function roles()
    {
        return $this->hasMany(Role::class);
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题