Skip to content
David Ciulla edited this page Nov 7, 2026 · 2 revisions

Events

Laravex's event system provides a simple observer implementation, allowing you to decouple various aspects of your application. The event dispatcher is an OTP GenServer running as Laravex.Events.Dispatcher. Listeners can be synchronous module functions or queued via the Queues.


Registering Events and Listeners

Define your event-to-listener map in app/Providers/EventServiceProvider by implementing a listen/0 function that returns a map:

defmodule App.Providers.EventServiceProvider do
  def listen do
    %{
      App.Events.UserRegistered => [
        App.Listeners.SendWelcomeEmail,
        App.Listeners.ProvisionAccount
      ],
      App.Events.OrderShipped => [
        App.Listeners.UpdateInventory
      ]
    }
  end
end

On boot (or when event:cache loads the cached map), each listener in the map is registered with the dispatcher automatically.


Defining Events

An event is any Elixir struct (or atom). The simplest form is a plain struct:

defmodule App.Events.UserRegistered do
  defstruct [:user_id, :email]
end

Defining Listeners

A listener is a module that exports a handle/1 function:

defmodule App.Listeners.SendWelcomeEmail do
  def handle(%App.Events.UserRegistered{email: email}) do
    App.Mail.WelcomeMail
    |> Map.put(:to, email)
    |> Laravex.Mail.Mailer.send()
  end
end

Dispatching Events

Pass a struct to Laravex.Events.Dispatcher.dispatch/1, or an atom with an optional payload:

# Dispatch a struct event
Laravex.Events.Dispatcher.dispatch(%App.Events.UserRegistered{
  user_id: user.id,
  email: user.email
})

# Dispatch an atom event with a plain payload
Laravex.Events.Dispatcher.dispatch(App.Events.OrderShipped, %{order_id: 42})

The dispatcher matches the event's module name against registered listeners and invokes each in turn. Synchronous listeners are called inline; queued listeners are pushed to the queue (see Queued Listeners below).


Registering Listeners at Runtime

You can register anonymous function listeners or additional module listeners after boot:

Laravex.Events.Dispatcher.listen(App.Events.UserRegistered, fn event ->
  IO.puts("User registered: #{event.email}")
end)

Laravex.Events.Dispatcher.listen(App.Events.OrderShipped, App.Listeners.NotifyAdmin)

Queued Listeners

To defer a listener to the Queues, use the Laravex.Events.ShouldQueue macro:

defmodule App.Listeners.ProcessPodcast do
  use Laravex.Events.ShouldQueue

  def handle(event) do
    # This runs inside a queue worker
    App.Services.PodcastProcessor.process(event.podcast_id)
  end
end

use Laravex.Events.ShouldQueue injects a should_queue?/0 function that returns true. When the dispatcher encounters a listener module for which should_queue?() is truthy, it pushes a Laravex.Events.CallQueuedListener job (which calls listener.handle(data)) to the queue instead of invoking the listener synchronously.

You can override the flag on a per-module basis:

defmodule App.Listeners.LogOnly do
  use Laravex.Events.ShouldQueue, queue: false   # run synchronously

  def handle(event), do: Logger.info(inspect(event))
end

Event Caching

The event map from EventServiceProvider.listen/0 can be pre-compiled and stored to disk so the dispatcher doesn't re-read it on every boot.

# Write bootstrap/cache/events.term
./artisan event:cache

# Remove the cache file
./artisan event:clear

The cached file is an Erlang binary term at bootstrap/cache/events.term. On next boot, Laravex.Events.EventCache.load!/1 reads the file and re-registers all listeners.


Listing Events

./artisan event:list

This prints every event and its listeners — combining those from EventServiceProvider.listen/0 and any registered at runtime via Dispatcher.listen/2. Output is sorted alphabetically by event name:

App.Events.OrderShipped
  ⇂ App.Listeners.UpdateInventory
App.Events.UserRegistered
  ⇂ App.Listeners.ProvisionAccount
  ⇂ App.Listeners.SendWelcomeEmail

Inspecting Registered Listeners

Retrieve the runtime listener map programmatically:

Laravex.Events.Dispatcher.listeners()
# => %{App.Events.UserRegistered => [...], ...}

Conditional Dispatch

# Only dispatch when condition is truthy
Laravex.Events.Dispatcher.dispatch_if(post.published, :post_published, %{post: post})

# Only dispatch when condition is falsy
Laravex.Events.Dispatcher.dispatch_unless(post.draft, :post_published, %{post: post})

until — First Responding Listener

# Calls each listener in turn; stops at the first non-nil return value
result = Laravex.Events.Dispatcher.until(:find_handler, %{key: "value"})

Mirrors Laravel's Dispatcher::until. Useful when you want the first willing listener to handle the event and all subsequent listeners to be skipped.


See Also

  • Queues — job queue powering queued listeners
  • Broadcasting — broadcasting events to the client
  • Artisan-Console — event:list, event:cache, event:clear, make:event, make:listener

Clone this wiki locally