Create an EVENT and Listener in Laravel 7

This laravel 7 tutorial help to understand event and listeners.The laravel event allows to subscribe and listen for various events that occur in your application.

The Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. By-default these directory not exist into the /app folder, It creates automatically by generating event and listeners using command lines.

How To Generate EVENT and Listener in Laravel 7

The EventServiceProvider included with your Laravel application provides a convenient place to register all of your application’s event listeners. The listen property contains an array of all events (keys) and their listeners (values).

I have already shared Events And Listeners Example Using Laravel 5.6.This tutorial help to integrate event and listener in laravel, I will also let you know to call event from controller method.

There are below method that help to create event and listener class, and stored file into the app/Events and app/Listeners directory.You can get more information from Official Docs.

Make the event and listeners class entry into the Providers/EventServiceProvider.php

Option 1:

php artisan event: generate

Above command will create file into respective folder like, TestEvent into app/Events and TestEventListener into app/Listeners.

Option 2:

We can also generate event and listener files by following command –

php artisan make:event TestEvent
php artisan make:listener TestEventListener --event="TestEvent"

The event File code is –

The full event file code is below –

How To Define handle file

Now modified handle() method into App\Listeners\TestEventListener.php file, that will have some program, that will execute when the even will occurred.

How To Dispatch Event In Laravel

The dispatching event is very easy in laravel, You need to just pass the event class object into event() method and event will fire when the testEvent() method will call.