Php

Events and Listeners Example Using Laravel 9

Events and listeners are two awesome functionality to handle decouple modules in a web application. The laravel Events follow the observer pattern, That allows you to subscribe and listen for various events that occur in your application.

Laravel use Artisan to create event and listeners. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. initially, these folders do not exist but generate events and listeners folders using Artisan console commands.

What are Laravel Events and Listeners?

An event is an action or occurrence that will happen in your application. The Application will raise events when something happens, The listeners will listen to that event and react accordingly. The listener is a program or method that will execute some logic or operation.

Let’s Create Events in Laravel 9

We will create a simple event that fired an event on call of rest API endpoints. The listener will listen to that event and print a log message.

You can also check other recommended tutorials of Lumen/Laravel,

Step 1: We will generate TestEvent and TestEventListener file using the CLI command.

php artisan event:generate

The above command will create a file into the respective folder like, TestEvent into app/Events and TestEventListener into app/Listeners.

Aleternate way, you can also create above file using below command:

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

Step 2: We will make one entry into app/Providers/EventServiceProvide.php file, this file is used to register all of your application’s event listeners.

protected $listen = [
        ...,
  ..,
       'App\Events\TestEvent' => [
        'App\Listeners\TestEventListener',
      ],
    ];

Now modified handle() method into TestEventListener.php file, that will have some program, that will execute when the event will occur.

Related Post

How to Dispach Event in Laravel

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

use App\Events\Event;
use App\Events\TestEvent;

public function testEvent(){
try {
  
  Log::info('=== Hello  ========');
  Event::fire(new TestEvent());
  return 'hello';
  } catch(Exception $ex) {
  Log::info('Error'. $e->getMessage());

  return $ex;
  }
}

Above will sync manner to execute logic, if the someting is complex and time consuming process to execute on occurance of event, then mostly developer recommended use Laravel Queue for background lengthy process.

How to Use Larevel Event in Queue

This step will help to add event into queue so that listeners method will process into the background of laravel application. I will use same EVENT and add into Laravel queue.

You can use any available queue driver like db,redist or beanstakd. You can get more information of laravel queue from create Queue and Run Jobs using worker in Lumen/Laravel

We will create Job file using below command:

php artisan make:job MyJob

Above command will create jobs/MyJob.php file and file would be like below:

<?php

namespace App\Jobs;
use Log;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class MyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

    /**
     * Execute the job.
     *
     * @return void
     */    public function handle()
    {
        //
      Log::info("hello! I am queue handler!!!");
    }
}

We will change Listener TestEventListener.php file and added job instance into handler method.

<?php

namespace App\Listeners;

use App\Events\Event;
use App\Events\TestEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Log;
use App\Jobs\MyJob;

class TestEventListener extends Event implements ShouldBroadcast 
{
    /**
     * Create the event listener.
     *
     * @return void
     */    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  TestEvent  $event
     * @return void
     */    public function handle(TestEvent $event)
    {
        //
      dispatch(new MyJob());
      Log::info('=== TestEventListener  ========');
    }
}

We will dispaced the event in the controller file as below:

public function testEventQueue(){
      try {
         Event::fire(new TestEvent());
         return 'hello Queue';
      } catch(Exception $ex) {
         Log::info('Error'. $e->getMessage());

         return $ex;
      }
    }

Now run queue manually using below command, You can add auto pickuo of jobs using supervisord, You can get more information Configure supervisord on Linux for Laravel Jobs Queue

php artisan queue:work

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories