How to use Laravel Event System to implement login log? This article mainly introduces the use of Laravel event System how to achieve 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. We hope to help you.
Let's take a look at the detailed introduction below:
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 {use 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->agent = $agent; $this->ip = $ip; $this->timestamp = $timestamp; } public Function GetUser () {return $this->user; } public Function GetAgent () {RetuRN $this->agent; } public Function 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-de Fault '); }}
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 event public function handle (Lo Ginevent $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 ()) {//bot $login _info[' device_type ') = ' robot '; $login _info[' device '] = $agent->robot (); Robot name} else {//Desktop device $login _info[' device_type ') = ' desktop '; }//INSERT INTO Database db::table (' Login_log ')->insert ($login _info); } }
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.
Related recommendations:
Explore how the middleware of Laravel is implemented
Explains how to customize cryptographic services in Laravel
Some practical tips for improving the performance of Laravel 5