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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题