【问题标题】:Laravel Auth::user() session custom?Laravel Auth::user() 会话自定义?
【发布时间】:2018-05-07 19:48:10
【问题描述】:

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

在角色表中有 id 和 name。

在 user_role 表中有 user_id 和 roll_id。

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

【问题讨论】:

  • 您不设置会话,而是将角色附加到用户...当您注册用户时,您可以将该用户的角色设置为您喜欢的任何角色。或者,如果您有一些管理面板,那么管理员可以将角色分配给该用户。这就是它的完成方式。还是你有别的想法?
  • 但是是否可以在会话中显示滚动?
  • 当您将角色分配给用户时,您总是可以得到它...只需调用 Auth::user()->role 或 auth()->user()->role跨度>
  • 我没有在用户表中分配角色,但我现在将用户表与角色表建立了关系,如何从该表中获取会话中的数据

标签: php laravel laravel-5 session-variables


【解决方案1】:

在用户模型中创建关系

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);

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

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

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

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

这将返回 true 或 false,然后您可以使用该信息做一些事情。

【讨论】:

    猜你喜欢
    • 2020-11-06
    • 2019-12-10
    • 2020-07-16
    • 2021-08-17
    • 2018-01-18
    • 2021-06-28
    • 2015-05-13
    • 2019-03-29
    • 2020-01-23
    相关资源
    最近更新 更多