【问题标题】:How can get authenticated user role from pivot table via Vue JS in Laravel如何通过 Laravel 中的 Vue JS 从数据透视表中获取经过身份验证的用户角色
【发布时间】:2019-11-14 22:04:47
【问题描述】:

您好,我正在尝试获取经过身份验证的用户的角色。我有 3 个表:用户、角色和角色用户(枢轴)。具有多对多关系(见下文)。当我在 vue 组件中调用 v-if="$gate.isSuperAdmin() 时出现错误:

“类型错误:this.user.roles 未定义”

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

**Role Model
public function users()
{
    return $this->belongsToMany('App\User');
}

** App.blade.php(master layout)
  <body>

<div id="app"></div>
  @auth
    <script>
        window.user = @json(auth()->user()) 
        //window.user = @json(auth::user()->roles) (I tried this as well)
    </script>   
  @endauth

<script src="{{ mix('/b_assets/entry-point.js') }}"></script>

** Gate.js
export default class Gate{

constructor(user) {
    this.user = user;
}

  isAdmin() {
     return this.user.slug === 'admin';
  }

  isSuperAdmin() {
    return this.user.roles.slug === 'superadmin';
  }  
}

然后在 App.js 中我导入 Gate.js

/ Get Authenticated User
 import Gate from '@/Gate';
 Vue.prototype.$gate = new Gate(window.user);

【问题讨论】:

  • 尝试在刀片中打印auth()-&gt;user()-&gt;roles 并查看输出。还要检查 Vue 开发者工具栏中的 this.user 并检查错误消息。
  • @MikeRoss, auth()->user()->roles 输出当前用户角色,这是正确的。但是如何在我的 Gate.js 文件中调用用户角色呢?
  • 先试试console.log(this.user.roles),看看角色是否打印正确。附上控制台输出格式。
  • @MikeRoss,我叫 window.user = @json(auth()->user()->roles) window.user = @json(auth()->user()->roles ) zzzz

标签: laravel vue.js


【解决方案1】:

检查以下事项

1) User.php 您的模型文件并确保它已加载 roles 关系。

protected $with = ['roles']

在控制台打印user 数据并查看roles 已加载。

2) 你在isAdmin() 代码上有错字

isAdmin() {
     //return this.user.slug === 'admin'; 
     return this.user.roles.slug === 'admin';
}

这应该可以正常工作。

【讨论】:

  • 你太棒了。我能够获得用户的角色。但是,我将不得不调用例如 return this.user.roles[0].slug。有时用户可能有多个角色。不指定数组索引,如何循环查找条件中传入的角色?
  • 您可以在 vue 中创建一个方法来循环角色或在 php 端执行此操作并发送附加用户模型的标志。例如,如果用户是超级管理员,请在 php 端检查并将每个角色的标志附加到用户数据中。
猜你喜欢
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 2019-11-29
  • 2017-11-29
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多