Laravel Intermediate Auth & Jobs · 6 min read

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

Syntax
LessonPublished::dispatch($lesson);

Example

app/Events/LessonPublished.php
<?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

  1. The event carries the lesson that was published.
  2. Dispatchable adds the static dispatch method.
  3. The listener handle method receives the event.
  4. It forgets the cached count.
  5. The controller will dispatch the event after a successful publish.
  6. The listener does not decide whether publish is allowed.
  7. Register the pair with Event::listen or discovery.
  8. 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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…