douyuan4697 2018-03-03 23:38
浏览 150
已采纳

Laravel Auth :: user() - > roles() - > get()为空

I was starting on learning some Laravel. I am working on a website where you can create an account, which can have roles, and depending on what roles you have, you can do stuff. What it is isn't important, but let me explain the whole situation.

I do have 3 tables:

  • One called users, which stores information about all users.
  • One called roles, which stores information about all roles (just id + name)
  • One called user_roles, which stores which roles users have. It has an id column (for PK), an user_id column (as FK to users.id) and a role_id column (as FK to roles.id)

I do have 2 models:

Model Users:

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'mood'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
     protected $hidden = [
         'password', 'remember_token',
     ];

     public function roles() {
         return $this->belongsTo('App\Role');
     }
}

Model Roles:

class Role extends Model
{
    protected $table = 'roles';

    protected $fillable = ['role'];
}

Now, what I did in one of my controller is add the following line:

var_dump(Auth::user()->roles()->get())

So I got my user, I am logged in, I did add a role and I did add a new user_roles row (with my user ID and the ID of the role I added). However, the var_dump still returns an empty array instead of the role I have. I don't understand what I did wrong

  • 写回答

2条回答 默认 最新

  • drduh44480 2018-03-03 23:53
    关注

    User - Role is an M:M relationship. One user can have many roles; and also, one role can be used by many users.

    For many-to-many relationships Laravel (Eloquent) provides the belongsToMany method. Here is the docs: https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

    Therefore, you need to replace this method in your User class:

     public function roles() {
         return $this->belongsTo('App\Role');
     }
    

    with this:

     public function roles() {
         return $this->belongsToMany('App\Role');
     }
    

    Also, you need to tell Laravel what name the pivot table has. You can either pass it as a second argument to the belongsToMany method, or just name it roles_users and Laravel will figure it out (how does it do that is also in the docs).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?