我做了以下代码,用于在进行注销事件时将一些数据保存到用户表,现在需要将相同的数据保存到“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');
});
}
应用\监听\ 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();
}
答案 0 :(得分:2)
为login_histories表创建模型
<强> 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()
]);
}