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

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 –

The TestEventListener.php file will have below initial code –

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

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

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.

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.