首页 > 解决方案 > Laravel 使用 Auth::user() 从另一个表中获取数据

问题描述

我对 Laravel 比较陌生。

我有 2 张不同的桌子。rolesusers

我希望能够Auth::user()->role->perms获得用户角色的权限。

在我的User.php我有以下

public function role(){
        return $this->belongsTo(Role::class, 'role');
    }

在我的Role.php我有以下

public function users() {
        return $this->HasMany(User::class);
    }

这是我的create_users_table.php

Schema::connection('panel')->create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('steam64');
            $table->string('steamName');
            $table->string('name');
            $table->string('role')->default('user');
            $table->rememberToken();
        });

这是我的create_roles_table.php

Schema::connection('panel')->create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('role');
            $table->json('perms')->default('{"full_perms":0, "some_other_perms":0}');
            $table->integer('immunity')->default(10);
        });

当我使用{{Auth::user()->role->perms}}时,我得到以下错误Trying to get property 'perms' of non-object

希望这是足够的信息。如果没有,我可以提供更多信息。

标签: phplaravellaravel-7laravel-7.x

解决方案


在用户表角色列不能是字符串它必须是角色表的 id 并且应该是无符号的


推荐阅读