在Laravel

时间:2017-10-13 07:33:17

标签: php laravel laravel-5 logout

登录事件发生时,代码为Login Event Listener

我还将Logout Event Listener设为与Login 1相同的设计。

它可以工作,但它只是在同一个表中创建另一行。

那我怎样才能将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();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

在这种情况下,只需找到具有用户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在用户表中是唯一的

答案 1 :(得分:1)

您可以使用soft delete添加deleted_at列。

然后你可以像这样查询

$log = LogoutHistory::where('user_name', $event->user->name)->delete();

这会在deleted_at列中添加时间戳。