Introduction to the method of using Laravel Event system to complete login log record

Source: Internet
Author: User
Tags event listener log log
This article mainly introduces the use of the Laravel event System how to implement log records of the relevant information, the article introduced in very detailed, for everyone has a certain reference learning value, the need for friends below to see it together.

This article describes the use of Laravel event system to implement log records of the relevant content, share it for everyone to refer to, the following to see the detailed introduction:

Clear requirements

Logging a log log typically requires the following information:

    • Client Agent Information

    • Client IP Address

    • Access IP Locations

    • Logon Hours

    • Login User Information

Establish tools

After you've identified your needs, find the tools you need, based on each requirement.

    • Demand 1 jenssegers/agent to meet our requirements

    • Demand 2 laravel directly underRequest::getClientIp()

    • Requirement 3 Zhuzhichao/ip-location-zh This package can meet the requirements

    • Requirement 4 time ()

    • Requirement 5 Login User model

Start

Implemented with the Laravel event subscription system, you need to implement a logon event and a logon event listener.

Generating events and listeners

The Laravel command line supports automatic generation of events and listeners, adding events that need to be implemented in App\providers\eventserviceprovider:


protected $listen = [   ...,  //Add login events and corresponding listeners, an event can be bound to multiple listeners  ' app\events\loginevent ' = [  ' app\ Listeners\loginlistener ',],];

Run command: php artisan event:generate events and listeners are automatically generated, and existing events and listeners do not change.

Logon events (event)

Looking back at the requirements, our login events require 5 points of information to be recorded in the event, so the event is designed as follows:


namespace App\events;use Illuminate\broadcasting\channel; Use Illuminate\queue\serializesmodels; Use Illuminate\broadcasting\privatechannel; Use illuminate\foundation\events\dispatchable; Use Illuminate\broadcasting\interactswithsockets;use app\models\user; Use Jenssegers\agent\agent;class loginevent {dispatchable, interactswithsockets, serializesmodels;/** * @var user Model */protected $user; /** * @var Agent Agent Object */protected $agent; /** * @var String IP address */protected $ip; /** * @var int logon timestamp */protected $timestamp; /** * Pass this information when instantiating an event */Public function __construct ($user, $agent, $ip, $timestamp) {$this->user = $user; $this->agen t = $agent; $this->ip = $ip; $this->timestamp = $timestamp; Public Function GetUser () {return $this->user;} public Function getagent () {return $this->agent;} public funct  Ion GetIP () {return $this->ip;} public Function Gettimestamp () {return $this->timestamp;}/** * Get the Channels The event should broadcast on.* * @return Channel|array */Public Function Broadcaston () {return new Privatechannel (' Channel-default ');}} 

Record the required information in an event and implement the Get method for that information.

Login Listener (Listener)

In the listener, get the information that is passed to the event, log the information to the database, and implement the following:


Namespace App\listeners;use app\events\loginevent;class Loginlistener {//handle method handles the event public function handle ( Loginevent $event) {//Gets the information saved in the event $user = $event->getuser (); $agent = $event->getagent (); $ip = $event->getip (); $timestamp = $event->gettimestamp (); Login information $login _info = [' IP ' + $ip, ' login_time ' + $timestamp, ' user_id ' = $user->id]; Zhuzhichao/ip-location-zh contains methods to obtain IP geolocation $addresses = \ip::find ($IP); $login _info[' address ' = implode (' ', $addresses); Jenssegers/agent method to extract the agent information $login _info[' device ' = $agent->device ();   Device name $browser = $agent->browser (); $login _info[' browser ') = $browser. ' ' . $agent->version ($browser); Browser $platform = $agent->platform (); $login _info[' platform ') = $platform. ' ' . $agent->version ($platform); Operating system $login _info[' language '] = implode (', ', $agent->languages ()); Language//device type if ($agent->istablet ()) {//tablet $login _info[' device_type ') = ' tablet ';} else if ($agent->ismobile()) {//Convenience device $login _info[' device_type ' = ' mobile ';} else if ($agent->isrobot ()) {//crawler robot $login _info[' device_t  Ype '] = ' robot '; $login _info[' device '] = $agent->robot (); Bot name} else {//Desktop device $login _info[' device_type ') = ' desktop ';}//INSERT INTO Database db::table (' Login_log ')->insert ($login _inf O); } }

In this way, the listener is complete, and each time a logon event is triggered, a login is added to the database.

Triggering events

The event is triggered by a global event() method, and event() the parameter of the method is an instance of the event:


namespace App\controllers; ... use app\events\loginevent; Use jenssegers\agent\agent; Class Authcontrooler extends Controller {... public function login (Request $request) {//Login implementation ...//login successful, trigger event (new L Oginevent ($this->guard ()->user (), New Agent (), \request::getclientip (), Time ())); ...  } }

Queue Listener

Sometimes the listener takes some time-consuming action, and the listener should be queued in conjunction with the Laravel queue system, provided the queue is configured and the queue processor is turned on.

Queueing is very simple, just the listener implements the Shouldqueue interface, namely:


namespace App\listeners; ... use illuminate\contracts\queue\shouldqueue; Class Loginlistener implements Shouldqueue {/** * failed retry count * @var int */Public $tries = 1; ...}

Summarize

Laravel's event system is still very elegant, the same event can be easily added various types of listeners, and each listener does not interfere with each other, the decoupling is very strong. Plus the queue system, you can easily handle a number of follow-up tasks.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.