Create events and listeners: Use the Artisan command to generate UserRegistered events and SendWelcomeEmail and LogUserRegistration listeners; 2. Define event classes: Inject user instances into the UserRegistered constructor for listeners to access; 3. Write listener logic: SendWelcomeEmail sends welcome emails, and LogUserRegistration records user registration logs; 4. Register events and listeners: bind events and listeners in the $listen array of EventServiceProvider; 5. Distribute events: After the user is registered, the UserRegistered event is triggered through event() or Event::dispatch() to make the listener automatically execute; 6. Optional enable automatic event discovery: Set shouldDiscoverEvents to return true and run the event:cache command to automatically register the listener; 7. Best practice: Keep the listener single responsibility, and time-consuming tasks use the ShouldQueue interface to implement queue processing to avoid writing complex logic in events. This mode improves application maintainability and scalability by decoupling business logic, and is suitable for notification, logging, analysis and other scenarios.
Laravel Events and Listeners are a powerful way to make your application more modular and maintained by decoupling actions from the code that triggers them. Instead of writing long, tightly coupled logic in your controllers or models, you can dispatch events and let listeners react to them. This tutorial walks you through setting up and using events and listeners in Laravel with a practical example.

What Are Events and Listeners?
- Event : Something that happened in your app (eg, a user registered).
- Listener : A class that reacts to that event (eg, send a welcome email, log activity).
This pattern follows the observer pattern , allowing one part of your app to notify others without knowing who's listening.
Step 1: Generate an Event and Listener
Laravel makes it easy to create events and listeners using Artisan commands.

Let's say we want to send a welcome email and log user registration.
Create the Event
php artisan make:event UserRegistered
This creates a file: app/Events/UserRegistered.php

Create the Listener
php artisan make:listener SendWelcomeEmail --event=UserRegistered php artisan make:listener LogUserRegistration --event=UserRegistered
This creates:
-
app/Listeners/SendWelcomeEmail.php
-
app/Listeners/LogUserRegistration.php
You can also create listeners without specifying the event and wire them manually later.
Step 2: Define the Event Class
Open app/Events/UserRegistered.php
. It should look like this:
<?php namespace App\Events; use App\Models\User; 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 UserRegistered { use Dispatchable, InteractsWithSockets, SerializesModels; public $user; public function __construct(User $user) { $this->user = $user; } public function broadcastOn() { return new PrivateChannel('channel-name'); } }
We're passing the $user
model to the event so listeners can access it.
Step 3: Write the Listener Logic
Open app/Listeners/SendWelcomeEmail.php
:
<?php namespace App\Listeners; use App\Events\UserRegistered; use Illuminate\Support\Facades\Mail; use App\Mail\WelcomeEmail; class SendWelcomeEmail { public function handle(UserRegistered $event) { Mail::to($event->user->email)->send(new WelcomeEmail($event->user)); } }
Make sure you have a WelcomeEmail
Mailable:
php artisan make:mail WelcomeEmail
Similarly, for logging:
<?php namespace App\Listeners; use App\Events\UserRegistered; use Illuminate\Support\Facades\Log; class LogUserRegistration { public function handle(UserRegistered $event) { Log::info('New user registered: ' . $event->user->email); } }
Step 4: Register the Event and Listeners
Open app/Providers/EventServiceProvider.php
.
In the $listen
array, map the event to its listeners:
protected $listen = [ 'App\Events\UserRegistered' => [ 'App\Listeners\SendWelcomeEmail', 'App\Listeners\LogUserRegistration', ], ];
This tells Laravel which listeners should run when UserRegistered
is dispatched.
After making changes here, run:
php artisan event:cache
(for production; not required in local during development)
Step 5: Dispatch the Event
Now, trigger the event from your controller or model.
In your RegisterController
or wherever user registration happens:
use App\Events\UserRegistered; use Illuminate\Support\Facades\Event; // After user creation event(new UserRegistered($user)); // Or using the Event facade Event::dispatch(new UserRegistered($user));
Example in a controller method:
public function register(Request $request) { $user = User::create($request->validated()); event(new UserRegistered($user)); return redirect('/dashboard'); }
When this runs, both listeners will execute.
Optional: Event Discovery
If you don't want to manually register events in EventServiceProvider
, Laravel can auto-discover them.
Enable it in EventServiceProvider
:
public function shouldDiscoverEvents() { return true; }
Laravel will scan the Listeners
directory and auto-register event-listener pairs based on type-hinting in the handle()
method.
Then you don't need to list them in $listen
.
Run:
php artisan event:cache
Best Practices
- Keep listeners focused: One job per listener.
- Use queueable listeners for slow tasks (like sending emails):
class SendWelcomeEmail implements ShouldQueue { use Queueable; }
Make sure your listener uses the Queueable
trait and implements ShouldQueue
.
- Avoid heavy logic in events; use them just to signal.
Summary
Events and listeners help you write cleaner, more scalable Laravel apps by separating concerns. You've now:
- Created an event (
UserRegistered
) - Made listeners (
SendWelcomeEmail
,LogUserRegistration
) - Registered them in
EventServiceProvider
- Dispatched the event from your code
This pattern is great for audit logging, notifications, analytics, and more.
Basically, if something happens and other parts of your app need to know — use events.
The above is the detailed content of Laravel events and listeners tutorial. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction

Using the correct PHP basic image and configuring a secure, performance-optimized Docker environment is the key to achieving production ready. 1. Select php:8.3-fpm-alpine as the basic image to reduce the attack surface and improve performance; 2. Disable dangerous functions through custom php.ini, turn off error display, and enable Opcache and JIT to enhance security and performance; 3. Use Nginx as the reverse proxy to restrict access to sensitive files and correctly forward PHP requests to PHP-FPM; 4. Use multi-stage optimization images to remove development dependencies, and set up non-root users to run containers; 5. Optional Supervisord to manage multiple processes such as cron; 6. Verify that no sensitive information leakage before deployment

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

To build a flexible PHP microservice, you need to use RabbitMQ to achieve asynchronous communication, 1. Decouple the service through message queues to avoid cascade failures; 2. Configure persistent queues, persistent messages, release confirmation and manual ACK to ensure reliability; 3. Use exponential backoff retry, TTL and dead letter queue security processing failures; 4. Use tools such as supervisord to protect consumer processes and enable heartbeat mechanisms to ensure service health; and ultimately realize the ability of the system to continuously operate in failures.
