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 –

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.

Leave a Reply

Your email address will not be published. Required fields are marked *