gpt4 book ai didi

php - Laravel 中发生注销事件时发布时间戳数据

转载 作者:行者123 更新时间:2023-12-02 03:46:07 27 4
gpt4 key购买 nike

下面的代码是登录事件发生时的登录事件监听器

我还制作了注销事件监听器,与登录事件监听器的设计相同。

它有效,但它只是在同一个表中创建另一行。

那么我怎样才能将Logout数据制作到表中发布的登录数据的同一行?是否可以将数据发布到登录数据保存行的deleted_at

谢谢:)

LogSuccessfulLogin.php

<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;

use App\LoginHistory;

class LogSuccessfulLogin
{
/**
* Create the event listener.
*
* @param Request $request
* @return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}

/**
* Handle the event.
*
* @param Login $event
* @return void
*/

public function handle(Login $event)
{

LoginHistory::create([
'user_name' => $event->user->name,
'last_login_at' => date('Y-m-d H:i:s'),
'last_login_ip' => $this->request->ip(),
]);

$user = $event->user;
$user->last_login_at = date('Y-m-d H:i:s');
$user->last_login_ip = $this->request->ip();
$user->save();
}
}

LogSuccessfulLogout.php

<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Logout;
use Illuminate\Http\Request;

use App\LogoutHistory;
use App\LoginHistory;
use \Carbon\Carbon;
use DateTime;

class LogSuccessfulLogout
{
/**
* Create the event listener.
*
* @param Request $request
* @return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}

/**
* Handle the event.
*
* @param Login $event
* @return void
*/
public function handle(Logout $event)
{
$log = LoginHistory::where('user_name', $event->user->name)->first();

if($log)
{
//logout timestamp store.
$log->last_logout_at = date('Y-m-d H:i:s');
$log->save();

//calculate time_worked
$strStart = Carbon::now();
$strEnd = $log->last_login_at;
$dteStart = new DateTime($strStart);
$dteEnd = new DateTime($strEnd);
$dteDiff = $dteStart->diff($dteEnd);
// print $dteDiff->format("%H:%I:%S");
// dd($dteDiff);
$log->time_worked = $dteDiff->format("%H:%I:%S");
$log->save();
}
}
}

最佳答案

在这种情况下,很简单找到带有用户 ID 的 LogoutHistory 然后更新它:

public function handle(Logout $event)
{
$log = LogoutHistory::where('user_name', $event->user->name)
->latest('last_login_at')
->first();

if($log) {
$log->last_logout_at = date('Y-m-d H:i:s');
$log->save();
}
}

PS:假设user_name在用户表中是唯一的

关于php - Laravel 中发生注销事件时发布时间戳数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46724774/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com