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 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行