一、執(zhí)行,php artisan make:event AdminLoginEvent 命令,Laravel目錄\app\Events會生成AdminLoginEvent.php文件,
二、我們先在\app\Providers目錄下找到EventServiceProvider.php文件,該文件內(nèi)有一個Events-Listeners數(shù)組來保存事件和監(jiān)聽者的映射關(guān)系:
protected $listen = [
'App\Events\AdminLoginEvent' => [
'App\Listeners\AdminLogListener',
],
];
三、執(zhí)行,php artisan event:generate 命令,Laravel\app\Listeners目錄下會生成AdminLogListener.php文件在文件里寫一些業(yè)務:
?php
namespace App\Listeners;
use App\Business\AdminLogBiz;
use Illuminate\Contracts\Queue\ShouldQueue;
use Common;
class AdminLogListener implements ShouldQueue
{
private $adminLogBiz;
/**
* Create the event listener.
* UserLogListener constructor.
* @param AdminLogBiz $adminLogBiz
*/
public function __construct(AdminLogBiz $adminLogBiz)
{
$this->adminLogBiz = $adminLogBiz;
}
/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handle($event)
{
$admin = $event->admin;
$data = [];
$data['admin_id'] = $admin->id;
$data['admin_username'] = $admin->truename;
$data['remote_ip'] = Common::getClientIP();
$data['location'] = isset($ipInfo['city']) ? $ipInfo['city'] : '';
$userName = empty($admin->truename) ? $admin->mobile : $admin->truename;
$data['log_code'] = 'login';
$data['log_content'] = $userName . '用戶登陸';
$this->adminLogBiz->add($data);
}
}
四、觸發(fā)這個事件,在用戶登錄的地方:
use App\Events\AdminLoginEvent;
/**
* 登錄
*
* @param Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function signin(Request $request)
{
$username = $request->username;
$password = $request->password;
if (Auth::guard('admin')->attempt(array('username' => $username, 'password' => $password))) {
if (Auth::guard('admin')->user()->status) {
$this->logout($request);
return redirect('/admin/login')->with('error', '賬號已被鎖定');
} else {
event(new AdminLoginEvent(Auth::guard('admin')->user()));
return redirect('admin/index');
}
} else {
return redirect('admin/login')->with('error', '賬戶或密碼錯誤');
}
}
這樣就完成了整個用戶登錄的監(jiān)聽事件,當用戶登錄的時候表就會添加用戶登錄的信息。
以上這篇laravel實現(xiàn)登錄時監(jiān)聽事件,添加登錄用戶的記錄方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- laravel 5.3 單用戶登錄簡單實現(xiàn)方法
- Laravel 自動生成驗證的實例講解:login / logout