1

我目前正在记录用户的最后登录时间戳并将 ip 记录到用户表中。我在 laravel 7 中的身份验证控制器登录功能中做到了这一点。像这样:

            $user->last_login = Carbon::now()->toDateTimeString();
            $user->last_login_ip = $request->getClientIp();
            $user->save();

但当前项目我使用 laravel fortify 包。我还在学习这个包。记录用户登录时间戳和 ip 的最佳方法是什么。?

谢谢你

4

1 回答 1

2

现在才想通,我使用了 Laravel 登录事件。和它的工作。

//class event
<?php

namespace App\Events;

use Illuminate\Auth\Events\Login;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Carbon\Carbon;
class UpdateUserLastLoginDate
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Login  $event
     * @return void
     */
    public function handle(Login $event)
    {
        try {
            $user = $event->user;
            $user->last_login = Carbon::now()->toDateTimeString();
            $user->last_login_ip = request()->getClientIp();
            $user->save();
        } catch (\Throwable $th) {
            report($th);
        }
    }
}

//在事件服务提供者中

<?php

namespace App\Providers;


/** ***/
use Illuminate\Auth\Events\Login;
use App\Events\UpdateUserLastLoginDate;
/** ***/

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
       /** ***/
        Login::class => [
            UpdateUserLastLoginDate::class
        ],
/** ***/

    ];

  
}
于 2021-03-24T05:49:01.303 回答