我想存储用户的注销日期时间,因为我创建了事件,该事件在单击注销按钮监听器事件被调用后工作正常。下面我编写了代码来存储注销时间。
<?php
namespace App\Listeners;
use App\UserTrack;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
class LoggedOutListener
{
public function handle($event)
{
$user = $event->user;
$user = Auth::user();
$track = UserTrack::where('user_id','=',$user->id)->orderBy('id', 'desc')->first();
$end = $track->last_logout = Carbon::now();
$start = Carbon::createFromFormat('Y-m-d H:i:s', $track->last_login);;
$track->timestamp = $start->diffInSeconds($end);
$track->save();
}
}
我想在会话过期之前调用该事件来存储注销时间。
您将中间件添加到注销路由:
<?php
...
Route::get('/logout', [AuthenticatedSessionController::class, 'destroy'])
->middleware([RegisterLogoutEventMiddleware::class])
->name('logout');
并创建您的中间件:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class RegisterLogoutEventMiddleware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
event(LogoutEvent::class);
return $next($request);
}
}
之后您可以创建
LogoutEvent
事件并将其注册到 EventServiceProvider
:
protected $listen = [
...
LogoutEvent::class => [
LoggedOutListener::class,
],
];