0

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

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();
}
4

1 回答 1

2

为 login_histories 表创建模型

登录历史.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 。可以通过多种方式完成

保存登录历史记录而不是用户

命名空间应用\监听器;

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()
    ]);
}
于 2017-10-12T21:09:41.663 回答