Prefix
- Laravel Version 5.8 or above
- PHP Version 7.1.3 or above
Overview
Hello friends, today we will discuss the Event and Event Listener and how we can add on laravel and manage Events. There are so many blogs for Event and Event Listener but in this blog, we will discuss what is an Event and Event Listener is and how we can add and remove Events in our project.
What is an Event?
In Computer terminology, an Event is an action detected by a program. Events can be user actions such as moving a cursor, clicking a mouse button, or pressing a key.
What is an Event Listener?
An Event Listener is a function in a program that waits for an event to occur. The listener is a program that reacts to an input or signal by calling the event’s handler.
E.g: When a user is registered successfully at that time sending an email.
When to use Event?
An Event is mainly used to perform repeated tasks in your project. Suppose you are working on any project and you have some tasks that you have to perform more than once, at that time you can use an Event.
Let’s take an example, In our project, we want to send emails to a particular user when the user signs up or purchases a product from our website. Here if we don’t use an Event, we have to perform separate codes to send mail for sign up and purchase of product.
In Laravel, best practice is that we have to create one event for sending emails and create a different Listener and set “listen” property to identify which event is executed.
Create Event and Event Listener
In Laravel we can easily create an Event and Event Listener. This mainly is covered in three parts.
- Registering Events & Listeners
- Generating Events & Listeners
- Dispatching Event
Let’s discuss all the parts of an Event and Event Listener in detail.
Registering Events & Listeners
In Laravel, we have an App/Providers/EventServiceProvider class to register our events and listeners.In this class “listen” property contains an array of all events (keys) and their listeners(values).You can add one or more events
In this array as per your requirement.
Example :-
protected $listen = [ 'App\Events\CheckPayment' => [ 'App\Listeners\CheckPaymentListner', ], ];
Generating Events & Listeners
In laravel Generating Events & Listeners there are two method that is as follow:
- Generate an Event and Listeners using EventServiceProvider
- Create Listener and Event using command
- Generate an Event and Listeners using EventServiceProvider
Step (1) : In the first step you have to define Event and Listener in Providers/EventServiceProvider class.You can define multiple Events and Listener in this array as explained above.
Step(2) : After that we need to generate an Event and Listener using the following command.This command will generate ‘CheckPayment’ event in App/event path and create ‘CheckPaymentListener’ listener at App\Listeners location.=> php artisan event:generate - Create Listener and Event using command
Step(1): In this way we have to execute the following command to create an event and listener.The following command will generate “ChkPayment” event at App/Events.=> php artisan make:event ChkPaymentAbove command will create a “ChkPayment” file something like this :ChkPayment :<?php namespace App\Events; use App\Models\Post; 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 CheckPayment { use Dispatchable, InteractsWithSockets, SerializesModels; public $paymentvalue; public $fireornot; public function __construct($value,$fire) { $this->fireornot = $fire; $this->paymentvalue = $value; } public function broadcastOn() { return new PrivateChannel('channel-name'); } }
The following command will generate Listener that is “ChkPaymentEventListener” for event “ChkPayment”.”CheckPaymentListener” provide one method that is “handle”.In this method you can define your action(logic) to perform when this event is called.
=> php artisan make:listener ChkPaymentEventListener –event=”ChkPayment”ChkPaymentEventListener :
<?php namespace App\Listeners; use App\Events\CheckPayment; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class CheckPaymentListner { public function __construct() { } public function handle(CheckPayment $event) { if($event->fireornot){ echo "payment amount is : ". $event->paymentvalue; } else{ echo "sorry event is not fired"; return false; } echo "<br>This is check payment event "; } } step(2) : After the creation of Listener and Event we have to register our Listener and Event in App/Providers/EventServiceProvider class. protected $listen = [ 'App\Events\CheckPayment' => [ 'App\Listeners\CheckPaymentListner', ], ];
- Generate an Event and Listeners using EventServiceProvider
Dispatching Event
In the last step we have to dispatch(execute) our event.To dispatch an event, you may pass an instance of the event helper.The helper will dispatch the event to all of its registered listeners.Since the event helper is globally available, you may call it from anywhere in your application. We can pass arguments to the event and access in our defined Event and Listener class.
Please find below file examples:
Controllers/frontend/PaymentController :
<?php namespace App\Http\Controllers\frontend; use App\Events\CheckPayment; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class PaymentController extends Controller { public function payment(Request $Request){ event(new CheckPayment(100,true)); } }
web.php(Route) :
<?php Route::get('payment', 'frontend\PaymentController@payment')->name('payment')
Note (To Stop Event) :-
In laravel if you want to stop execution of an event you need to return false in the handle method of Listener class.In our example,we have defined a ‘fireornot’ variable in “CheckPayment” event and we will passed value in PaymentController here we have passed second argument as boolean value that is true or false.
Here, the passing argument is true so it will execute an event and display the following output.
Output :
Payment amount is : 10
This is check payment event
Conclusion
I hope this blog is useful to all those who want to add Events in laravel. In this blog, I have tried to cover all possibilities regarding Events. It is the best practice to add Event and Event Listener so that the code stays optimized and can take advantage of code reusability. Once you have created any Event it can be accessed by the entire application.