我想计算用户使用Laravel中的事件登录的次数。
我定义了这个事件:
<?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()
{
//
}
/**
* 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');
}
}
并且在EventServiceProvider中我有以下内容:
<?php namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
class EventServiceProvider extends ServiceProvider {
/**
* The event handler mappings for the application.
*
* @var array
*/
protected $listen = [
'auth.login' => [
'App\Handlers\Events\AuthLoginEventHandler'
]
];
/**
* Register any other events for your application.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
* @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
//
}
}
更新:
我将postLogin()从trait覆盖到AuthController:
<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers;
/**
* Create a new authentication controller instance.
*
* @param \Illuminate\Contracts\Auth\Guard $auth
* @param \Illuminate\Contracts\Auth\Registrar $registrar
* @return void
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
Log::info('Logged in User from AuthController');
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
}
这不适用于我的Laravel 5.0,我不知道为什么,除了使用事件之外,除了使用事件之外还有其他任何计算用户登录的方法吗?
我正在检查日志,当我尝试Log :: info(&#39;登录&#39;)时,没有任何内容。在引导方法中,它来自日志。
答案 0 :(得分:1)
首先,因为您已将某些内容添加到提供程序中,您需要清除以前编译的源代码(缓存以加快加载时间)。
$ php artisan clear-compiled
其次,您的代码有计数问题,
$user->login_counter = 1; <-- set count to 1 ??
$user->save(); <--- then SAVE?
$user->increment('login_counter'); <--- INCREMENT for what?
相反,它应该是这样的
$user->login_counter += 1;
$user->save();
确保在迁移中您拥有login_counter
$table->integer('login_counter')->unsigned()->default(0);
然后就行了!