Laravel Events and Listeners
Lesson 24 of 33 in the Laravel learning path.
How do I run follow-up work when a lesson is published without stuffing it in the controller?
An event announces that something happened. A listener reacts. The controller does not call every follower itself.
Publishing a lesson may clear a cache and notify a channel. Those are listeners, not extra lines that make store harder to read.
Syntax & Parameters
LessonPublished::dispatch($lesson);
Example
<?php
namespace App\Events;
use App\Models\Lesson;
use Illuminate\Foundation\Events\Dispatchable;
class LessonPublished
{
use Dispatchable;
public function __construct(public Lesson $lesson)
{
}
}
namespace App\Listeners;
use App\Events\LessonPublished;
use Illuminate\Support\Facades\Cache;
class ForgetCatalogCount
{
public function handle(LessonPublished $event): void
{
Cache::forget('lessons.published-count');
}
}
Expected Output
After LessonPublished::dispatch($lesson), ForgetCatalogCount deletes the lessons.published-count cache key.
Line-by-Line Walkthrough
- The event carries the lesson that was published.
- Dispatchable adds the static dispatch method.
- The listener handle method receives the event.
- It forgets the cached count.
- The controller will dispatch the event after a successful publish.
- The listener does not decide whether publish is allowed.
- Register the pair with Event::listen or discovery.
- A slow listener should implement ShouldQueue.
Common Pitfalls & Security
This is easy to misuse.
- Doing the work in the event constructor runs it even when nobody listens.
- A listener that publishes again can loop.
- Forgetting to register the listener means the cache stays stale.
- A queued listener must only receive serializable data. The model is fine if it uses SerializesModels.
Best Practices & Modern Standards
Dispatch after the database write commits.
Keep listeners small. Queue the ones that send mail or call the network.
Real-World Use
Publishing a lesson clears the homepage count through a listener, so the controller stays a publish action.
Frequently Asked Questions
Where do I dispatch?
After the update that set published_at has succeeded.
How is a listener found?
Event discovery looks for a handle method, or you register the pair yourself.
Can a listener queue?
Yes. Implement ShouldQueue so the request does not wait.
Should the event check a policy?
No. Authorize in the controller before you dispatch.