2016-08-24 50 views
1

我想要統計用戶在Laravel中使用事件登錄的次數。如何使用衛星跟蹤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

我也改變了身份驗證()函數,這和它的工作:

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')); 
} 

而現在的計數器工作,這樣我就可以跟蹤用戶登錄時,你會想到什麼傢伙,這是一種解決方案嗎?對我來說似乎工作正常,爲什麼我們使用事件時,我們可以做到這一點簡單?

我想聽聽有沒有人有更好的解決方案