Laravel 5.1 — get user’s login status, simple application of event, monitoring and Middleware

Time:2020-1-17

There are many aspects of events, such as logging in, buying goods, searching, viewing articles, and so on. After the listener listens to the event, it performs some operations.LaravelThe observer mode is used to implement this monitoring mechanism. Now we will explain an event through a user login, monitor an event and trigger the whole process of some operations.

Registering Events / Listeners

First, inApp/Providers/EventServiceProvider.phpRegister the mapping between events and listeners in. In the following three mapping relationships, we only useLoginEventandLoginSuccess

protected $listen = [
    'App\Events\LoginEvent' => ['App\Listeners\LoginSuccess'],
    'App\Events\LogoutEvent' => ['App\Listeners\LogoutSuccess'],
    'App\Events\UserAccess' => ['App\Listeners\UserAccess']
];

Then, execute in the root directoryartisan

$ php artisan event:generate

After the command is executed successfully, theApp/EventsandApp\ListenersLower generationApp/Events/LoginEventandApp/Listeners/LoginSuccessetc.phpfile

Define event class

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class LoginEvent extends Event
{
    use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    function __construct()
    {
        
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}

stayLoginEventNothing has changed in the event, and it doesn’t need to be changed

Defining listeners

Now inApp/ListenersOne of themLoginSuccess.phpMonitor, for the future, we areApp/ListenersCreate a basic listening class listenerbase.php

<?php
namespace App\Listeners;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Services\Statut;


class ListenerBase
{    
    /**
    * The statut intance
    *
    * @var App\Services\Statut
    */
    protected $statut;

    /**
    * Create a listener event
    *
    * @param App\Service\Statut $statut
    * @return void
    */
    function __construct()
    {
        $this->statut = new Statut;
    }
}
?>

ListenerBase.phpInstantiated aStatutClass, thisStatutClass is in the app / services folder, which we will use next.


Now comesApp/Listeners/LoginSuccess.php

<?php

namespace App\Listeners;

use App\Events\LoginEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class LoginSuccess extends ListenerBase
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @param  LoginEvent  $event
     * @return void
     */
    public function handle(LoginEvent $event)
    {   
        $this->statut->setLoginStatut($event);
    }
}

LoginSuccessInheritedListenerBase, in the handle method$this->statut->setLoginStatutGot the status of the logged in user

Statut.php

stayApp/ServicesNew ChinaphpfileStatut.php, and then in this file, it mainly defines several methods to get the status of the current login user. When an event is triggered, it will executeStatut.phpActions in files

<?php
namespace App\Services;

/**
* 
*/
class Statut
{
    
    function __construct()
    {
        # code...
    }

    /**
    * Set the login user statut
    *
    * @var App\Event\LoginEvent
    * @return void
    */
    public function setLoginStatut($event){
        Session() - > put ('statut ', auth() - > user() - > role - > slug); // auth() - > user() will have a value only after the user logs in
    }

    /**
    * Set visitor statut
    *
    * @return void
    */
    public function setVisitorStatut(){
        session()->put('statut', 'visitor');
    }

    /**
    * Set the statut
    *
    * @return void
    */
    public function setStatut(){
        if(!session()->has('statut')){
            session()->put('statut', auth()->check() ? auth()->user()->role->slug : 'visitor');
        }
    }
}
?>

OK, after the event and listener are completed, we need to trigger the operation. Here we use middleware(Middleware)

Defining Middleware

UseartisanCommand to create MiddlewareApp/Http/Middleware/App.php

$ php artisan make:middleware App

After successful execution, use the global methodevent

<?php

namespace App\Http\Middleware;

use Closure;
use App\Events\LoginEvent;

class App
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {   
        Event (New loginevent); // instantiate app / events / useraccess,

        return $next($request);
    }
}

Finally, I willAppMiddleware is registered in kernel.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \App \ http \ middleware \ app:: class, // APP Middleware
    ];

After completing the above operation, you can get the login status of the user. stayStatut.phpWe divide the user status intovisitoradmin,user, display different contents according to different states of login users. For example, if it isadmin, he can enter the background and perform some operations, if yesuserperhapsvisitor, then he can only browse some pages


Conclusion:

Understand what you want to do, what kind of purpose you want to achieve, and clear thinking in the process of operation.


Recommended Today

RCAST 35: add type to currency

– font ALT: Simsun; MSO font charset: 134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 680460288 22 0 262145 0;} @font-face {font-family:”Cambria Math”; panose-1:2 4 5 3 5 4 6 3 2 4; mso-font-charset:1; mso-generic-font-family:roman; mso-font-format:other; mso-font-pitch:variable; mso-font-signature:0 0 0 0 0 0;} @font-face {font-family:Calibri; Variable; Ose-1: 216301111; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 680460288 22 0 262145 0;} /\* Style […]