当前位置:首页 > CMS教程 > 其它CMS > 列表

laravel实现登录时监听事件,添加登录用户的记录方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-12-25 16:15:43 浏览: 评论:0 

今天小编就为大家分享一篇laravel实现登录时监听事件,添加登录用户的记录方法,具有很好的参考价值,希望对大家有所帮助,一起跟随小编过来看看吧。

一、执行,php artisan make:event AdminLoginEvent 命令,Laravel目录\app\Events会生成AdminLoginEvent.php文件,

二、我们先在\app\Providers目录下找到EventServiceProvider.php文件,该文件内有一个Events-Listeners数组来保存事件和监听者的映射关系:

  1. protected $listen = [ 
  2.   'App\Events\AdminLoginEvent' => [ 
  3.     'App\Listeners\AdminLogListener'
  4.   ], 
  5. ]; 

三、执行,php artisan event:generate 命令,Laravel\app\Listeners目录下会生成AdminLogListener.php文件在文件里写一些业务:

  1.  
  2. namespace App\Listeners; 
  3.  
  4. use App\Business\AdminLogBiz; 
  5. use Illuminate\Contracts\Queue\ShouldQueue; 
  6. use Common; 
  7.  
  8. class AdminLogListener implements ShouldQueue 
  9.   private $adminLogBiz
  10.  
  11.   /** 
  12.    * Create the event listener. 
  13.    * UserLogListener constructor. 
  14.    * @param AdminLogBiz $adminLogBiz 
  15.    */ 
  16.   public function __construct(AdminLogBiz $adminLogBiz
  17.   { 
  18.     $this->adminLogBiz = $adminLogBiz
  19.   } 
  20.  
  21.   /** 
  22.    * Handle the event. 
  23.    * 
  24.    * @param object $event 
  25.    * @return void 
  26.    */ 
  27.   public function handle($event
  28.   { 
  29.     $admin = $event->admin; 
  30.     $data = []; 
  31.     $data['admin_id'] = $admin->id; 
  32.     $data['admin_username'] = $admin->truename; 
  33.     $data['remote_ip'] = Common::getClientIP(); 
  34.     $data['location'] = isset($ipInfo['city']) ? $ipInfo['city'] : ''
  35.     $userName = emptyempty($admin->truename) ? $admin->mobile : $admin->truename; 
  36.     $data['log_code'] = 'login'
  37.     $data['log_content'] = $userName . '用户登陆'
  38.     $this->adminLogBiz->add($data); 
  39.   } 

四、触发这个事件,在用户登录的地方:

  1. use App\Events\AdminLoginEvent; 
  2. /** 
  3.  * 登录 
  4.  * 
  5.  * @param Request $request 
  6.  * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector 
  7.  */ 
  8. public function signin(Request $request
  9.   $username = $request->username; 
  10.   $password = $request->password; 
  11.   if (Auth::guard('admin')->attempt(array('username' => $username'password' => $password))) { 
  12.     if (Auth::guard('admin')->user()->status) { 
  13.       $this->logout($request); 
  14.       return redirect('/admin/login')->with('error''账号已被锁定'); 
  15.     } else { 
  16.       event(new AdminLoginEvent(Auth::guard('admin')->user())); 
  17.       return redirect('admin/index'); 
  18.     } 
  19.   } else { 
  20.     return redirect('admin/login')->with('error''账户或密码错误'); 
  21.   } 

这样就完成了整个用户登录的监听事件,当用户登录的时候表就会添加用户登录的信息。

Tags: laravel监听 laravel添加登录用户

分享到: