Laravel使用Auth :: user()从另一个表获取数据

时间:2020-08-08 00:03:07

标签: php laravel laravel-7 laravel-7.x

我是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

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

2 个答案:

答案 0 :(得分:0)

因此,您需要在角色表上定义user_id,最好定义删除用户后角色将要发生的事情。

create_roles_table.php

 Schema::connection('panel')->create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('role');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->json('perms')->default('{"full_perms":0, "some_other_perms":0}');
            $table->integer('immunity')->default(10);
        });

还删除$ table-> string('role')-> default('user');从用户表中,您不需要。

答案 1 :(得分:0)

在用户表的角色列中不能为字符串,它必须是角色表的ID,并且应为未签名