我想计算用户使用Laravel中的事件登录的次数。
我正在使用第三方库' satellizer '进行身份验证,我已经定义了一个AuthLoginEventHandler,如下所示:
<?php namespace App\Handlers\Events;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
use App\User;
use Illuminate\Support\Facades\Log;
class AuthLoginEventHandler {
/**
* Create the event handler.
*
* @return void
*/
public function __construct()
{
Log::info('Logged in User is working from constructor');
}
/**
* Handle the event.
*
* @param User $user
* @param $remember
* @return void
*/
public function handle(User $user, $remember)
{
Log::info('Logged in');
$user->login_counter = 1;
$user->save();
$user->increment('login_counter');
}
}
在AuthenticationController中我有:
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials','status'=>false], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token','status'=>false], 500);
}
Log::info('Logged in User from JWT');
Event::fire(new AuthLoginEventHandler());
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
问题是当我从AuthenticationController中的authenticate()函数触发事件时,handle()方法永远不会被调用。
我可以看到正在调用构造函数而不是句柄函数,我在这里缺少什么,还有其他方法可以实现这样的事情!
由于
答案 0 :(得分:0)
我确实将authentication()函数更改为此函数并且正在运行:
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials','status'=>false], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token','status'=>false], 500);
}
$user = Auth::user();
$user->increment('login_counter');
$user->update();
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
现在计数器正在运行,所以我可以跟踪用户登录,您认为这些人是什么类型的解决方案?对我来说似乎工作得很好,为什么我们可以这么简单地使用事件?
我想听听是否有人有更好的解决方案