Search

What Is Event Listener in Laravel and How to Create It ?

  • Share this:
post-title

Hello, today I want to talk about Events and Listeners in Laravel, in programming to write a scalable, reusable and clean code, you need to follow some programming principles.

What is An Event?

Events are the ways we hook into the activities of our application, it is just a way to observe an activity, for instance, login, a class can be created to monitor the activity of login, when a user logs in, the event class can execute some functions.

What is A Listener?

A Listener is a class that listens to the events that they are mapped to and execute a task, that is they are the ones that perform a given task for an event.

STEP 1: Installing Laravel via Composer

You can ignore this step if you already have an application downloaded or else, run the following command to create a brand new laravel project.

composer create-project laravel/laravel {directory} 10.0 --prefer-dist

STEP 2: Configure Database Connection

In this type of project, we must give precedence to the database connection, generically it should be configured before getting started. Incorporate the following code in .env file with your database details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

STEP 3: Run the project

After downloaded new application or already installed then moved our application directory run the following command or using your own method

cd {directory}
php artisan serve

Visit the link to check the project running. Here we will go to link http://127.0.0.1:8000 and view the default homepage of Laravel.

home page

STEP 4: Registering Events & Listeners

The App\Providers\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 for registering all the events and listeners as key-value pairs. Define events and listeners as shown below.

App\Providers\EventServiceProvider.php
use App\Events\OrderShipped;
use App\Listeners\SendShipmentNotification;
 
/**
 * The event listener mappings for the application.
 *
 * @var array<class-string, array<int, class-string>>
 */
protected $listen = [
    OrderShipped::class => [
        SendShipmentNotification::class,
    ],
];

If you want to chek event list overall application so you can use event:list command display a list of all events and listeners registered by your application.

STEP 5: Generating Events & Listeners

event:generate Artisan command. This command will generate events or listeners that are listed in your EventServiceProvider that do not already exist

php artisan event:generate

The above command will generate two files, namely:

  • OrderShipped in app/Events
  • SendShipmentNotification in app/Listeners

Once done with the Laravel latest version events and listeners setup, now it’s time to get our hands on the logic part.

STEP 6: Define Event Logic

In this section, we will define the action (event) on which we want the set of logic to be performed by the listener; in our application, the action is creating a user. Open App\Events\OrderShipped.php and use the below code to pass the actual email address as $email to the __construct method of the OrderShipped class

public $email;

public function __construct($email)
{
    $this->email = $email;
}

The entire file will look like this.

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OrderShipped
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     */
    public $email;

    public function __construct($email)
    {
        $this->email = $email;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('channel-name'),
        ];
    }
}

STEP 7: Define Listener Logic: handle() method

Here, we will write actual logic for sending an email notification whenever the user is created. In App\Listeners\SendShipmentNotification.php, pass the OrderShipped $event parameter to handle() method so that we can have a value from the event. The logic within the handle() method will be executed whenever the event is called.

<?php

namespace App\Listeners;

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

class SendShipmentNotification
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(OrderShipped $event): void
    {
        print_r($event->email);
        //We can send a mail from here.
        echo ".. From Listeners";
        exit;
    }
}

STEP 8:Dispatch Event

After creating the event and listener, now it’s time to dispatch the event. It’s pretty straightforward; you just need to pass the event class object to the event() method. in call any where controller or api controller i am using UserController.php for demo 

php artisan make:controller UserController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Events\OrderShipped;
class UserController extends Controller
{
    
    public function index(){
        event(new OrderShipped('[email protected]'));
    }
}

STEP 9: Create route

All Laravel web routes are defined inside your web.php files, which are located in the routes directory. These files are automatically loaded by the framework. The routes

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('/order', [UserController::class, 'index']);
About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (53)