Laravel Auth::user() 会话自定义?

Laravel Auth::user() session custom?

我在数据库中有三个 table。一个是用户,第二个是角色,另一个是 user_role。

在角色 table 中有 ID 和名称。

在 user_role table 中有 user_id 和 roll_id.

现在我想在用户登录应用程序时设置会话。 llike Auth::user()->roll

在用户模型中创建关系

public function roles()
{
    return $this->belongsToMany(Role::class);
}

在角色模型中创建关系

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

然后你可以像这样给用户添加一个角色:

Auth::user()->roles()->attach(id_of_the_role_from_roles_table);

这将在 pivot table role_user 中创建一个新条目,然后您可以在用户模型中创建一个函数

public function hasRole($role)
{
    return $this->roles->contains('id', $role);
}

您可以在代码中的任意位置调用它。例如:

Auth::user()->hasRole(1);

这将 return 是真还是假,然后您可以使用该信息做一些事情。