laravel实现登录时监听事件,添加登录用户的记录方法
人气:0一、执行,php artisan make:event AdminLoginEvent 命令,Laravel目录\app\Events会生成AdminLoginEvent.php文件,
二、我们先在\app\Providers目录下找到EventServiceProvider.php文件,该文件内有一个Events-Listeners数组来保存事件和监听者的映射关系:
protected $listen = [ 'App\Events\AdminLoginEvent' => [ 'App\Listeners\AdminLogListener', ], ];
三、执行,php artisan event:generate 命令,Laravel\app\Listeners目录下会生成AdminLogListener.php文件在文件里写一些业务:
<?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); } }
四、触发这个事件,在用户登录的地方:
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', '账户或密码错误'); } }
这样就完成了整个用户登录的监听事件,当用户登录的时候表就会添加用户登录的信息。
以上这篇laravel实现登录时监听事件,添加登录用户的记录方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:
加载全部内容