SlideShare a Scribd company logo
Laravel 8
Events and
Listeners
With
Example




www.bacancytechnology.com
Introduction
Laravel provides a simple mechanism for
events and listeners so that whenever you
want to subscribe or listen to any event of
your application, you can do it easily. You
can register events with their listeners and
decide what you want them to do after a
particular action. For example, whenever a
new order is created, we wish to send a mail
or SMS to the seller. To simplify, we can say
an event is an action taken in the
application, and the listener is the operation
that responds to the event.


In this tutorial, we will learn and explore
Laravel 8 events and listeners. We will
develop a small demo application in which
we will send an email whenever a user is
created. In this scenario, we can say user
creation is an event, and the listener will
send an email on listening to the event.
Tutorial Goal:
Laravel 8
Event and
Listener
Before getting started with the
development part, let’s see what we are
building in this tutorial.
Register
Event and
Listener
The first step is to register the event and the
respective listener. For that, Laravel
provides an EventServiceProvider.php file
where you can define events and listeners.


The $listen property contains an array for
registering all the events and listeners as
key-value pairs. Define events and listeners
as shown below.


// EventServiceProvider.php


protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
'AppEventUserCreated' => [
'AppListenersSendEmail'
]
];
UserCreated in app/Events
SendEmail in app/Listeners
Once you register the event and listener,
run the below command to create the files
for the respective event and listener.
php artisan event:generate
The above command will generate two files,
namely:


Once done with the Laravel 8 events and
listeners setup, now it’s time to get our
hands on the logic part.
Define Event
Logic
In this section, we will define the action
(event) on which we want the set of logic to
be performed by the listener; in our demo
app, the action is creating a user.


Open AppEventsUserCreated.php and use
the below code to pass the actual email
address as $email to the __construct
method of the UserCreated class


// AppEventsUserCreated.php


public $email;
public function __construct($email)
{
$this->email = $email;
}




The entire file will look like this.
namespace AppEvent;
use IlluminateBroadcastingChannel;
use
IlluminateBroadcastingInteractsWithSock
ets;
use
IlluminateBroadcastingPresenceChannel;
use
IlluminateBroadcastingPrivateChannel;
use
IlluminateContractsBroadcastingShould
Broadcast;
use
IlluminateContractsQueueShouldQueue;
use
IlluminateFoundationEventsDispatchabl
e;
use IlluminateQueueSerializesModels;
class UserCreated implements
ShouldQueue
{
use Dispatchable, InteractsWithSockets,
SerializesModels;7i


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


/**
* Get the channels the event should broadcast on.
*
* @return IlluminateBroadcastingChannel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Here we inherit the ShouldQueue interface using
class UserCreated implements ShouldQueue.It will
automatically place the logic in the queue.
Define
Listener
Logic:
handle()
method
Here, we will write actual logic for sending
an email whenever the user is created. In
AppListenersSendEmail.php, pass the
UserCreated $event parameter to handle()
method so that we can have a value from
the event. The logic within the handle()
method will be executed whenever the
event is called.


public function handle(UserCreated $event)
{
print_r($event->email);
//We can send a mail from here
echo ".. From Listeners";
exit;
}
Dispatch
Event
After creating the event and listener, now
it’s time to dispatch the event. It’s pretty
straightforward; you just need to pass the
event class object to the event() method.


// UserController.php


event (new
UserCreated(“abc@gmail.com”));
Feel free to clone the repository and play
around with the code. You can find the
source code here.
Conclusion
I hope the tutorial Laravel 8 Events and
Listeners with Example was helpful for you.
For any queries and suggestions, feel free to
contact us. If you are a Laravel enthusiast,
you must check out the Laravel tutorials
page, where we provide various tutorials
with the source code.


Are you looking for skilled and experienced
Laravel developers with optimum problem-
solving skills? If yes, then you are just a
click away from hiring the best laravel
developers! Contact us today and hire
Laravel developer for your project.
Thank You
www.bacancytechnology.com

More Related Content

What's hot

Rack
RackRack
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
Raf Kewl
 
Java spring mysql without hibernate(2) (1)
Java spring mysql without hibernate(2) (1)Java spring mysql without hibernate(2) (1)
Java spring mysql without hibernate(2) (1)
AmedJacobReza
 
Laravel.IO A Use-Case Architecture
Laravel.IO A Use-Case ArchitectureLaravel.IO A Use-Case Architecture
Laravel.IO A Use-Case Architecture
Shawn McCool
 
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 TutorialAdventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
Joe Ferguson
 
How to deploy laravel application on aws ec2
How to deploy laravel application on aws ec2How to deploy laravel application on aws ec2
How to deploy laravel application on aws ec2
Katy Slemon
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
Viral Solani
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
Vikas Chauhan
 
Lampstack (1)
Lampstack (1)Lampstack (1)
Lampstack (1)
ShivamKumar773
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
Bukhori Aqid
 
Ruby On Rails Starter Kit
Ruby On Rails Starter KitRuby On Rails Starter Kit
Ruby On Rails Starter Kit
El Orabi Mohamed Ikbal
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
Christopher Pecoraro
 
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Lorvent56
 
My first WordPress Plugin
My first WordPress PluginMy first WordPress Plugin
My first WordPress Plugin
Abbas Siddiqi
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
Ahmad Fatoni
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
Darren Craig
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
Xiaoqi Zhao
 
New Component Patterns in Ember.js
New Component Patterns in Ember.jsNew Component Patterns in Ember.js
New Component Patterns in Ember.js
Matthew Beale
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
Singapore PHP User Group
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with Laravel
Michael Peacock
 

What's hot (20)

Rack
RackRack
Rack
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
 
Java spring mysql without hibernate(2) (1)
Java spring mysql without hibernate(2) (1)Java spring mysql without hibernate(2) (1)
Java spring mysql without hibernate(2) (1)
 
Laravel.IO A Use-Case Architecture
Laravel.IO A Use-Case ArchitectureLaravel.IO A Use-Case Architecture
Laravel.IO A Use-Case Architecture
 
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 TutorialAdventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
 
How to deploy laravel application on aws ec2
How to deploy laravel application on aws ec2How to deploy laravel application on aws ec2
How to deploy laravel application on aws ec2
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
Lampstack (1)
Lampstack (1)Lampstack (1)
Lampstack (1)
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
 
Ruby On Rails Starter Kit
Ruby On Rails Starter KitRuby On Rails Starter Kit
Ruby On Rails Starter Kit
 
RESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher PecoraroRESTful API development in Laravel 4 - Christopher Pecoraro
RESTful API development in Laravel 4 - Christopher Pecoraro
 
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
Laravel Starter Kit | Laravel Admin Template-ChandraAdmin
 
My first WordPress Plugin
My first WordPress PluginMy first WordPress Plugin
My first WordPress Plugin
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
 
New Component Patterns in Ember.js
New Component Patterns in Ember.jsNew Component Patterns in Ember.js
New Component Patterns in Ember.js
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with Laravel
 

Similar to Laravel 8 events and listeners with example

Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.
Nida Ismail Shah
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
James Gray
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
Payal Dungarwal
 
D8 dispatcher / subscriber
D8 dispatcher / subscriberD8 dispatcher / subscriber
D8 dispatcher / subscriber
joshirohit100
 
Sencha Touch MVC
Sencha Touch MVCSencha Touch MVC
Sencha Touch MVC
Neha Upadhyay
 
Writing User Stories for an Amazon Alexa app
Writing User Stories for an Amazon Alexa appWriting User Stories for an Amazon Alexa app
Writing User Stories for an Amazon Alexa app
Todd Kovalsky
 
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docxPlease look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
randymartin91030
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
How to integrate flurry in android
How to integrate flurry in androidHow to integrate flurry in android
How to integrate flurry in android
adityakumar2080
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
udithaisur
 
PATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event ModelPATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event Model
Michael Heron
 
Laravel Events And Queue
Laravel Events And QueueLaravel Events And Queue
Laravel Events And Queue
Vivek S
 
Login and private message
Login and private messageLogin and private message
Login and private message
caviar7571
 
Login and private message
Login and private messageLogin and private message
Login and private message
gueste832a8e
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Server Sent Events
Server Sent EventsServer Sent Events
Server Sent Events
Mohanad Obaid
 
Open social
Open socialOpen social
Open social
Tushar Gandhi
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
Richa Jain
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
simmis5
 
Java gui event
Java gui eventJava gui event
Java gui event
SoftNutx
 

Similar to Laravel 8 events and listeners with example (20)

Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
D8 dispatcher / subscriber
D8 dispatcher / subscriberD8 dispatcher / subscriber
D8 dispatcher / subscriber
 
Sencha Touch MVC
Sencha Touch MVCSencha Touch MVC
Sencha Touch MVC
 
Writing User Stories for an Amazon Alexa app
Writing User Stories for an Amazon Alexa appWriting User Stories for an Amazon Alexa app
Writing User Stories for an Amazon Alexa app
 
Please look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docxPlease look at the attach See.doc. I am getting this error all th.docx
Please look at the attach See.doc. I am getting this error all th.docx
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
How to integrate flurry in android
How to integrate flurry in androidHow to integrate flurry in android
How to integrate flurry in android
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
 
PATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event ModelPATTERNS06 - The .NET Event Model
PATTERNS06 - The .NET Event Model
 
Laravel Events And Queue
Laravel Events And QueueLaravel Events And Queue
Laravel Events And Queue
 
Login and private message
Login and private messageLogin and private message
Login and private message
 
Login and private message
Login and private messageLogin and private message
Login and private message
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
Server Sent Events
Server Sent EventsServer Sent Events
Server Sent Events
 
Open social
Open socialOpen social
Open social
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Java gui event
Java gui eventJava gui event
Java gui event
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Katy Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
 

Recently uploaded

Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
ScyllaDB
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
zjhamm304
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 

Recently uploaded (20)

Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...QA or the Highway - Component Testing: Bridging the gap between frontend appl...
QA or the Highway - Component Testing: Bridging the gap between frontend appl...
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 

Laravel 8 events and listeners with example

  • 3. Laravel provides a simple mechanism for events and listeners so that whenever you want to subscribe or listen to any event of your application, you can do it easily. You can register events with their listeners and decide what you want them to do after a particular action. For example, whenever a new order is created, we wish to send a mail or SMS to the seller. To simplify, we can say an event is an action taken in the application, and the listener is the operation that responds to the event. In this tutorial, we will learn and explore Laravel 8 events and listeners. We will develop a small demo application in which we will send an email whenever a user is created. In this scenario, we can say user creation is an event, and the listener will send an email on listening to the event.
  • 5. Before getting started with the development part, let’s see what we are building in this tutorial.
  • 7. The first step is to register the event and the respective listener. For that, Laravel provides an EventServiceProvider.php file where you can define events and listeners. The $listen property contains an array for registering all the events and listeners as key-value pairs. Define events and listeners as shown below. // EventServiceProvider.php protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], 'AppEventUserCreated' => [ 'AppListenersSendEmail' ] ];
  • 8. UserCreated in app/Events SendEmail in app/Listeners Once you register the event and listener, run the below command to create the files for the respective event and listener. php artisan event:generate The above command will generate two files, namely: Once done with the Laravel 8 events and listeners setup, now it’s time to get our hands on the logic part.
  • 10. In this section, we will define the action (event) on which we want the set of logic to be performed by the listener; in our demo app, the action is creating a user. Open AppEventsUserCreated.php and use the below code to pass the actual email address as $email to the __construct method of the UserCreated class // AppEventsUserCreated.php public $email; public function __construct($email) { $this->email = $email; } The entire file will look like this.
  • 12. use Dispatchable, InteractsWithSockets, SerializesModels;7i public $email; /** * Create a new event instance. * * @return void */ public function __construct($email) { $this->email = $email; } /** * Get the channels the event should broadcast on. * * @return IlluminateBroadcastingChannel|array */ public function broadcastOn() { return new PrivateChannel('channel-name'); } }
  • 13. Here we inherit the ShouldQueue interface using class UserCreated implements ShouldQueue.It will automatically place the logic in the queue.
  • 15. Here, we will write actual logic for sending an email whenever the user is created. In AppListenersSendEmail.php, pass the UserCreated $event parameter to handle() method so that we can have a value from the event. The logic within the handle() method will be executed whenever the event is called. public function handle(UserCreated $event) { print_r($event->email); //We can send a mail from here echo ".. From Listeners"; exit; }
  • 17. After creating the event and listener, now it’s time to dispatch the event. It’s pretty straightforward; you just need to pass the event class object to the event() method. // UserController.php event (new UserCreated(“abc@gmail.com”));
  • 18. Feel free to clone the repository and play around with the code. You can find the source code here.
  • 20. I hope the tutorial Laravel 8 Events and Listeners with Example was helpful for you. For any queries and suggestions, feel free to contact us. If you are a Laravel enthusiast, you must check out the Laravel tutorials page, where we provide various tutorials with the source code. Are you looking for skilled and experienced Laravel developers with optimum problem- solving skills? If yes, then you are just a click away from hiring the best laravel developers! Contact us today and hire Laravel developer for your project.