Laravel events and listeners tutorial with Real-world example [ Updated 2021 ]

    By: Thad Mertz
    2 years ago

    Hi everyone today we are going to see how Laravel Events can be used. It is an amazing feature provided by laravel by following few steps we will add user last login time to users table in Laravel.


    So to begin with

    First of all, you should have a project or localhost laravel setup. If you want to do everything from scratch check here first.

    Laravel Artisan Commands

    So to create an event we will be using laravel artisan command. You can give this file any name as you want. In our case, we are adding users last login time. So we will name our event file LastUserLogin.php.

    Let's Create Laravel Event

    php artisan make:event LastUserLogin;  
    

    We need to run the above command in our project directory. So

    CD INTO PROJECT FOLDER USING TERMINAL AND RUN ABOVE COMMAND

    After running the above command you should be getting a directory named Events.


    namespace App\Events;
    
    use Illuminate\Broadcasting\Channel;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Broadcasting\PrivateChannel;
    use Illuminate\Broadcasting\PresenceChannel;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    use App\User;
    use Illuminate\Support\Facades\Auth;
    
    
    class LastUserLogin
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
        public $user;
        public $id;
    
        /**
         * Create a new event instance.
         *
         * @param User $user
         */
        public function __construct($user)
        {
            $this->user = $user[0];
            $this->id = $user[0]->id;
    
        }
    
        /**
         * Get the channels the event should broadcast on.
         *
         * @return \Illuminate\Broadcasting\Channel|array
         */
        public function broadcastOn()
        {
            return new PrivateChannel('channel-name');
        }
    }
    
    

    You will get code like above in LastUserLogin.php

    In the above code, we are getting $user as a parameter and we are assigning it to $user and $id (Variables of LastUserLogin Class);

    Create a Laravel Listener

    Let's run another artisan command to make laravel event listener

    php artisan make:listener ListenerName --event=EventName  
    
    php artisan make:listener LastUserLoginListen --event=LastUserLogin
    

    Once you run artisan command to create listener you should get the file in the Listener folder as shown here.

    and LastUserLoginListen file should have code something like this.

    namespace App\Listeners;
    
    use App\Events\LastUserLogin;
    use App\User;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class LastUserLoginListen
    {
        /**
         * Create the event listener.
         *
         * @return void
         */
        public function __construct()
        {
            //
        }
    
        /**
         * Handle the event.
         *
         * @param  LastUserLogin  $event
         * @return void
         */
        public function handle(LastUserLogin $event)
        {
    
            $userUpdated = User::where('id',$event->id)->update(['last_login'=>now()]);
            if($userUpdated){
                return true;
            }
    
        }
    }
    

    So code in this file is straight forward. Note that we are using User Model to update the user field in Handle function.

    Handle function returns true if the field in database updates.

    !Note :

    Handle function getting "LastUserLogin" file(Event) as parameter.

    so you might ask how $event is providing id. the answer to this confusion is using/ Calling the event and passing value in the event. In this case, once a user logged in we fire the event . See the below-given code. It is in our Auth->Login controller.

    namespace App\Http\Controllers\Auth;
    
    use App\Events\LastUserLogin;
    use App\Http\Controllers\Controller;
    use App\Listeners\LogSuccessfulLogin;
    use Carbon\Carbon;
    
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    use Illuminate\Support\Facades\Auth;
    use Tests\Models\User;
    
    class LoginController extends Controller
    {
     
        use AuthenticatesUsers;
    
        /**
         * Where to redirect users after login.
         *
         * @var string
         */
        protected $redirectTo = '/';
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('guest')->except('logout');
        }
    
        public function authenticated( \Illuminate\Http\Request $request, \App\User $user ) {
            $user = \App\User::where('id',Auth::user()->id)->get();
    
            //WE ARE PASSING $USER IN EVENT IN BELOW GIVEN LINE
            event(new LastUserLogin($user));
        }
    
    }
    
    

    So if you see carefully we are passing logged in user data in LastUserLogin($user) as $user. which is used in the Listener as $event.

    Registering Laravel Event

    This step you should do once you have event and listener files ready. We need to define a link between Events and Listener file so these files can communicate as desired.

    Go in App/Providers and Look for EventServiceProvider.php

    Note register Event as shown here

    class EventServiceProvider extends ServiceProvider
    {
        /**
         * The event listener mappings for the application.
         *
         * @var array
         */
        protected $listen = [
            LastUserLogin::class => [
                LastUserLoginListen::class
            ],
        ];
    }
    

    Laravel Events Registered

    In the above code, we are adding value to an array.

    Our Event "LastUserLogin" And Our Listener "LastUserLoginListen"

    Conclusion

    so now when the user logs in. an event will fire that will send user info from database to listener. The listener will update the database with the login time of the user. You will need a database and you can update as you want using this feature.

    Hoping this post will help others do like and share.