Laravel

Parameterize Event and Listener in Laravel 7

This laravel 7 tutorial help to create parameterized event and listener, We can pass data to listener using event constructor, I will also create parameter for handler function.we will pass parameter which has listener method name that ll handle event.

Sometimes we need to call listener method based on parameter, We ll create method name as a parameter, that will passed from event call and handle into the listener class.

Let’s create an event and listener

Let’s add the event and listeners class entry into the Providers/EventServiceProvider.php

protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        'App\Events\TestEvent' => [
        'App\Listeners\TestEventListener',
      ],
    ];

Create event and listener using below command –

php artisan event:generate

Above command has been created files(TestEvent.php and TestEventListener.php) into respective folder like, TestEvent into app/Events and TestEventListener into app/Listeners.

The TestEvent.php file will have below initial code –

Related Post
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 TestEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

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

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

The TestEventListener.php file will have below initial code –

namespace App\Listeners;

use App\Events\TestEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

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

    /**
     * Handle the event.
     *
     * @param  TestEvent  $event
     * @return void
     */    public function handle(TestEvent $event)
    {
  
    }
}

Let’s modified event class constructor and attached parameters data and handler method.

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 TestEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

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

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

Let’s fetch the event parameters into the event handler method –

namespace App\Listeners;

use App\Events\TestEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

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

    /**
     * Handle the event.
     *
     * @param  TestEvent  $event
     * @return void
     */    public function handle(TestEvent $event)
    {
   $function = $event->operation;        
   $this->{$function}($event);
    }
 
 private function test1($event) {        
  Log::info('=== in method 1========');    
 }
 
 private function test2($event) {        
  Log::info('=== in method 2========');    
 }
}

How To Call Event in Controller File

We can trigger event from controller, utility, service etc file, We just need to pass required parameters into the event.

try {          
    event(new TestEvent('test1', $payload));       
 } catch(Exception $ex) {            
  Log::critical($ex);            
  return responseHandler('Unable to trigger test1 event', 400);      
 }

In the above code, We are using TestEvent and handler ll use 'test1' method and $payload is the data.

I hope you guys enjoyed this article.

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

2 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

8 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

8 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

9 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

9 months ago

Categories