post Laravel 事件处理程序中的一些事件数据

post some event data in Laravel event handler

我编写了以下代码,用于在发生注销事件时将一些数据保存到用户 table,现在需要将相同的数据保存到 "login_histories" table 以记录用户日志历史记录,那么如何在下面的代码中修改这个函数句柄呢? 谢谢:)

timestamp_create_login_histories_table.php

public function up()
{
    Schema::create('login_histories', function (Blueprint $table) {
        $table->engine = 'InnoDB';            
        $table->increments('id')->unsigned();

        $table->integer('user_id')->unsigned()->index();
        $table->timestamp('last_login_at')->nullable();
        $table->string('last_login_ip')->nullable();
        $table->timestamps();
        $table->softDeletes();

        $table->foreign('user_id')->nullable()->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
    });
}

App\Listeners\LogSuccessfulLogin.php

namespace App\Listeners;

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

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

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

一定要先做模型login_histories?然后我可以像下面的代码那样修改吗?

public function handle(Login $event)
{
    $login_histories = $event->login_histories;
    $login_histories->last_login_at = date('Y-m-d H:i:s');
    $login_histories->last_login_ip = $this->request->ip();
    $login_histories->save();
}

为 login_histories 创建模型 table

LoginHistory.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\User;

class LoginHistory extends Model
{
    protected $table = 'login_histories';

    protected $guarded = [];

    public function user()
    {
         return $this->belongsTo(User::class);//use user classs
    }
}

更新 App\Listeners\LogSuccessfulLogin.php 这样的东西。可以通过多种方式完成

保存登录历史而不是用户

命名空间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;
}

public function handle(Login $event)
{
    LoginHistory::create([
        'user_id' => $event->user->id,
        'last_login_at' => date('Y-m-d H:i:s'),
        'last_login_ip' => $this->request->ip()
    ]);
}