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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵