我有列last_activity,其中写入日期最后一个活动用户使用中间件。
如何检查在线用户以及何时退出?
中间件:
class LastActivityUser
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::check() && (\Auth::user()->last_activity < new \DateTime('-5 minutes'))) {
$user = \Auth::user();
$user->last_activity = new \DateTime;
$user->timestamps = false;
$user->save();
}
return $next($request);
}
}
用户模型中的代码:
public function online() {
return ($this->last_activity > new \DateTime('-5 minutes') && $user->check()) ? true : false;
}
$user->check
=&gt; Auth::check()
- 没有工作。我不需要使用Auth :: check(),我需要在其他用户上显示在线用户..但是Auth::check()
检查用户是否仅为当前的身份验证用户保留帐户..
答案 0 :(得分:3)
您可以使用中间件来检查在线用户
if(Auth::check()) {
$expiresAt = Carbon::now()->addMinutes(5);
Cache::put('user-is-online-' . Auth::user()->id, true, $expiresAt);
}
并检查用户:
public function isOnline()
{
return Cache::has('user-is-online-' . $this->id);
}
在视图中:
@if($user->isOnline())
user is online!!
@endif
也许这份文件可以帮助您:https://erikbelusic.com/tracking-if-a-user-is-online-in-laravel/
答案 1 :(得分:1)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class LastActivityUser
{
/**
* The authentication factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->check() && $this->auth->user()->last_activity < Carbon::now()->subMinutes(5)->format('Y-m-d H:i:s')) {
$user = $this->auth->user();
$user->last_activity = new \DateTime;
$user->timestamps = false;
$user->save();
}
return $next($request);
}
}
答案 2 :(得分:0)
您可以使用以下软件包来获取在线用户列表或确定用户是否在线。