Skip to content

Broadcasting

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

Broadcasting

Laravex's event broadcasting system lets you share server-side events with your client-side JavaScript application. The broadcaster is implemented as an OTP GenServer in Laravex.Broadcasting.Broadcaster and supports the log, null, array, and pubsub drivers.


Installation

Run the install command to scaffold the broadcasting config and channel routes:

./artisan install:broadcasting

This creates:

  • routes/channels.ex — channel authorization callbacks (equivalent to Laravel's routes/channels.php)
  • config/broadcasting.exs — broadcasting configuration

The generated config reads BROADCAST_CONNECTION from your environment:

%{
  "default" => Laravex.Env.get("BROADCAST_CONNECTION", "log"),
  "connections" => %{
    "log"    => %{"driver" => "log"},
    "null"   => %{"driver" => "null"},
    "array"  => %{"driver" => "array"},
    "pubsub" => %{"driver" => "pubsub"},
    "pusher" => %{
      "driver"  => "pusher",
      "app_id"  => Laravex.Env.get("PUSHER_APP_ID"),
      "key"     => Laravex.Env.get("PUSHER_APP_KEY"),
      "secret"  => Laravex.Env.get("PUSHER_APP_SECRET"),
      "cluster" => Laravex.Env.get("PUSHER_APP_CLUSTER", "mt1")
    }
  }
}

Configuration

Set BROADCAST_CONNECTION in your .env file:

BROADCAST_CONNECTION=pubsub
Driver Behaviour
log Writes the broadcast payload to the application log via Laravex.Log.Logger.info/2
null Silently discards all events
array Stores events in-memory (useful in tests — see Testing)
pubsub Delivers events to subscribed BEAM processes via Registry (in-process fan-out)
pusher ⚠️ Config scaffold only — no live Pusher HTTP client is implemented

PubSub Driver

The pubsub driver uses an Elixir Registry (Laravex.Broadcasting.PubsubRegistry) for in-process fan-out. Any process can subscribe to a channel and will receive broadcast events as {:laravex_broadcast, channel, message} messages.

# Subscribe the current process to a channel
Laravex.Broadcasting.Drivers.Pubsub.subscribe("orders.42")

# Unsubscribe from all channels
Laravex.Broadcasting.Drivers.Pubsub.unsubscribe()

Subscribed processes receive:

receive do
  {:laravex_broadcast, channel, %{event: event, data: data, at: at}} ->
    IO.inspect({channel, event, data})
end

Scope: pubsub is in-process only. Registry.dispatch delivers to PIDs within the same BEAM node — messages are not relayed across cluster nodes or to browser clients. Use Pusher or Ably (via their HTTP APIs) for real-time WebSocket delivery to end users.


Broadcastable Events

Implement the Laravex.Broadcasting.ShouldBroadcast behaviour on any module to make it broadcastable:

defmodule App.Events.OrderShipped do
  @behaviour Laravex.Broadcasting.ShouldBroadcast

  defstruct [:order_id, :status]

  @impl true
  def broadcast_on, do: "orders.#{@order_id}"   # or a list of channels

  @impl true
  def broadcast_as, do: "OrderShipped"

  @impl true
  def broadcast_with, do: %{order_id: @order_id, status: @status}
end

Broadcast the event by calling the ShouldBroadcast.broadcast/1 helper:

Laravex.Broadcasting.ShouldBroadcast.broadcast(App.Events.OrderShipped)

This calls broadcast_on/0, broadcast_as/0, and broadcast_with/0 on the module and dispatches one Broadcaster.event/3 call per channel.


Broadcasting Directly

You can also call the broadcaster directly without defining a broadcastable event:

# Broadcast to all subscribers of a channel
Laravex.Broadcasting.Broadcaster.event("orders.42", "OrderShipped", %{
  order_id: 42,
  status: "shipped"
})

# Broadcast to everyone except the current user (alias — same behaviour)
Laravex.Broadcasting.Broadcaster.to_others("orders.42", "OrderShipped", %{status: "shipped"})

The payload shape is Echo-compatible:

{
  "channel": "orders.42",
  "event": "OrderShipped",
  "data": { "order_id": 42, "status": "shipped" },
  "at": "2026-11-07T07:59:00Z"
}

Authorizing Channels

Private channels require authorization. Register channel patterns in routes/channels.ex using Laravex.Broadcasting.Channel.channel/2. The callback receives the authenticated user and a map of extracted URL parameters, and must return a truthy value to allow the connection.

defmodule Routes.Channels do
  def register do
    # Allow a user to subscribe only to their own private channel
    Laravex.Broadcasting.Channel.channel(
      "App.Models.User.{id}",
      fn user, %{"id" => id} ->
        not is_nil(user) and to_string(user.id) == to_string(id)
      end
    )

    # Allow any authenticated user to subscribe to the orders channel
    Laravex.Broadcasting.Channel.channel("orders", fn user, _params ->
      not is_nil(user)
    end)
  end
end

Pattern Matching

Channel patterns use {placeholder} segments. A pattern like "orders.{id}" matches a channel name of "orders.42" and passes %{"id" => "42"} to the callback. The number of dot-separated segments must match exactly.

Authorizing Programmatically

# Returns true or false
Laravex.Broadcasting.Channel.authorize("orders.42", current_user)

Listing Registered Channels

Laravex.Broadcasting.Channel.all()
# => ["App.Models.User.{id}", "orders"]

Testing

Switch the driver to array and use the fake helpers for assertions:

# Activate the in-memory driver
Laravex.Broadcasting.Broadcaster.fake()

# Trigger some action that broadcasts
Laravex.Broadcasting.Broadcaster.event("orders.42", "OrderShipped", %{order_id: 42})

# Inspect sent events
events = Laravex.Broadcasting.Broadcaster.sent()
# => [%{channel: "orders.42", event: "OrderShipped", data: %{order_id: 42}, at: "…"}]

See Also

Clone this wiki locally