Laravel,获取当前登录用户 [英] Laravel, get currently logged-in users

查看:862
本文介绍了Laravel,获取当前登录用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示应用程序中当前登录用户的列表.我想使用Laravel Auth方法.我正在查看API,但找不到类似的东西.

我可能需要遍历会话存储,然后将其与用户ID匹配.我说的对吗?

更新:忘记了,我将会话存储在数据库中.

解决方案

当前登录"是普通的旧会话无法做到的.让我解释一下原因:

会话是存储在服务器端的一堆数据,这些数据是通过cookie分配给用户的.该cookie保留在用户浏览器上,因此可以使会话保持活动状态.会话可以保持活跃"的几个月,而无需用户登录.

但是,可以在数据库中存储会话.

如您所见,Laravel保留了一个名为last_activity的字段,并且通过该字段,您应该能够检索最近15分钟内有活动的所有会话(或者您称之为其他名称).

检索这些记录时,data字段是会话数据的序列化表示.您可以unserialize($session_record->data)并检索用户ID.

根据您的Auth驱动程序,会话的用户ID可能具有不同的名称:

  • 对于雄辩的驾驶员,应为eloquent_login.
  • 对于流利的驱动程序fluent_login.
  • 对于您的Custom\AuthClass,应将其命名为custom_authclass_login.

I want to display a list of currently logged-in users in an app. I want to use Laravel Auth method. I'm looking at the API and I cannot find anything like it.

I would probably need to loop through the sessions store and then match it to a user ID. Am I right?

UPDATE: Forgot to mention, I'm storing sessions in the DB.

解决方案

"Currently logged in" is something you can't do with plain old sessions. Let me explain why:

A session is a bunch of data stored at server side which is assigned to an user through a cookie. That cookie remains on user browser and so it keeps the session active. Sessions can stay "alive" months without the user even logging in.

But, it's possible to store sessions on database.

As you can see, Laravel keeps a field called last_activity and, through that field, you should be able to retrieve all sessions that had activity within the last 15 minutes (or something else, you call it).

When your retrieve those records, the data field is a serialized representation of session data. You can unserialize($session_record->data) and retrieve the user id.

Depending on your Auth driver, session's user id may have different names:

  • For eloquent driver, it should be eloquent_login.
  • For fluent driver fluent_login.
  • For your Custom\AuthClass, it should be called custom_authclass_login.

这篇关于Laravel,获取当前登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆