Web Application

A Complete Guide to Events and Listeners in Laravel

Laravel is all about cool features. One such feature is the events and listeners which is very useful when you are dealing with emailing users or multiple registrations. For instance, you have a list of registered users. The sign-up, purchase of a product, adding it to the cart, enquiry can all be termed as events. Now, if you have to connect with the user or take an action after these events, you create listeners. Once you register a listener, Laravel sends it for the relevant events. In this blog, we show you how to create an event and Listeners in Laravel:

What is Event and Listener?

Event and Listener is a decoupling module which allows to transit two or more entities or methods without being connected or coupled. An Event can have multiple listeners and each listener will always watch for an event to be fired. A Listener is a method or small program which will execute once an event is occurred.

Laravel-Queue

Event and Listener is Laravel

Laravel’s events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Each event is stored into the app/Events folder and listener into the app/listeners folder. Now without doing any further delay let’s dive into a basic example of creating an event and listener in a Laravel.

Create Event and Listener

Step1: In Laravel we have to register our events and listeners into EventServiceProvider file which is available inside app/Providers, let’s modify our EventServiceProvider file mentioned as below.

/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
 'App\Events\TestEvent' => [
     'App\Listners\TestListener',
 ]
];

Step 2: Now that we have mentioned our first event and listener to EventServiceProvider we have to fire an artisan command to generate the TestEvent event and its TestListener listener files. This artisan command will generate all the events and listeners which are mentioned into the EventServiceProvider file.

php artisan event:generate

Step 3: Go to the TestEvent file under the app/Events and define a new protected variable and edit the construct method as mentioned below.

protected $name;

/**
* Create a new event instance.
*
* @return void
*/
public function __construct($name)
{
   $this->name = $name;
}

The TestEvent event will now be able to accept the $name parameter during its call and the $name can be called to any of its inherited listeners as it is later on assigned to the protected $name variable.

See also  9 Factors that Influence the Cost of Website Development

Step 4: Now let’s put some code into the Listener, open up the TestListener file from the app/Listener folder and add the below statement into the handle() method.

/**
* Handle the event.
*
* @param TestEvent $event
* @return void
*/
public function handle(TestEvent $event)
{
 Log::info("Hi, I'm {$event->name}");
}

This handler is not doing much but just logging the text into the storage/logs each time when the TestEvent is being fired.

Now that we learned how to create a basic Events and Listeners in Laravel let’s see how to fire the event.

How to use an Event

Using an event in Laravel is very simple lets see how.

Step 1: Create an TestController with the help of below artisan command

php artisan make:controller TestController

Step 2: Once the TestController file is created inside an app/Http/Controllers folder open up that file and create a test() method inside it as mentioned below.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Events\TestEvent;

class TestController extends Controller
{
 /**
 * Example to call Event from controller
 *
 */
 public function test()
 {
           event(new TestEvent('One Click'));
     return 'Hooray!!! You have fired your Event successfully';
 }
}

Step 3: Our TestController is ready to fire an event but before that we have to define a route for test() method, let’s create a route for it under the routes/web.php file.

Route::get('/test-event', 'TestController@test');

Step 4: Call the newly created route under any of your favorite browsers as localhost:8000/test-event and you will see a message “Hooray!!! You have fired your Event successfully” on your browser screen. Now open up today’s Laravel-log file from a storage/logs folder and inside that you will see text “Hi, I’m One Click”.

See also  The Benefits of Implementing DevOps Strategy in a Business

In this guide, we have covered the different types of events in Laravel, as well as how to create your own custom events to suit your needs. We have also discussed how to create event listeners and what type of data they receive when used.

We hope this information has been helpful. If you have any questions, reach out to an expert Laravel developer.

lets start your project

Related Articles