【发布时间】: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()->user()->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