Essentials / Broadcasting

Docs Essentials

Broadcasting Turbo Streams

So far, we've seen how to return Turbo Streams from handlers after a form submission over HTTP. In addition to that, we may also broadcast them over WebSockets, so every page that's looking at a post sees its new comments as they come in.

It's important to mention that this is an optional feature of Turbo and Turbo Laravel. You don't have to use Turbo Streams Broadcasting in order to use Turbo if you don't need it.

Broadcasts are usually triggered after a form submission. You may still return Turbo Streams over HTTP to the user that triggered the form submission, and only send the broadcast to other users. This way, the user making the change gets instant feedback instead of having to wait for the broadcast over WebSockets, which may involve queue workers.

Configuration

Broadcasting Turbo Streams relies on Laravel Rust's broadcasting, so configure a connection, such as Reverb, and Laravel Echo in the frontend. The turbo:install command sets up Echo for Reverb, as described in the Installation guide.

Streams are broadcast under the turbo.stream event name, which the turbo-echo-stream-source element listens for. Like Laravel Rust's one-off broadcasts, it's a dotted name rather than an event struct.

Listening to Broadcasts

A page subscribes to a channel with the turbo_stream_from template function:

jinja
{{ turbo_stream_from(post) }}

It renders a turbo-echo-stream-source element that subscribes to the post's private channel, private-posts.42, through Echo, and hands the streams it receives to Turbo. Pass type="public" or type="presence" for the other kinds of channels, or a string for a channel that isn't a model's:

jinja
{{ turbo_stream_from(post, type="public") }}
{{ turbo_stream_from("dashboard") }}

A model's channel is {table}.{route key}, so authorize it in src/routes/channels.rs with model binding:

rust
use laravel::broadcast::Channels;
use laravel::prelude::*;

pub fn routes(channel: &mut Channels) {
    channel.private("posts.{post}", post);
}

async fn post(post: Post) -> bool {
    post.published
}

Read the authorizing channels guide to check the user too.

Broadcasting Streams

Every stream has a broadcast_to method that returns a pending broadcast. Awaiting it sends the stream to the pages subscribed to the channels:

rust
use laravel::view::{data, view};
use turbo::{channel, stream};

stream::append("comments", view("comments.partials.comment", data! { comment }))
    .broadcast_to(&post) // private-posts.42
    .await?;

stream::remove(&comment).broadcast_to(channel::public(&post)).await?; // posts.42
stream::refresh().broadcast_to(channel::presence(&post)).await?;      // presence-posts.42
stream::update("stats", "42").broadcast_to("dashboard").await?;       // private-dashboard

A channel is a model, whose channel is {table}.{route key}, or a name. Both are private unless channel::public or channel::presence wraps them. Pass an array or a Vec to broadcast on several channels.

Broadcasts are queued and wait for the database transaction to commit, so pages never hear about a change that rolled back. The stream renders when it's awaited.

Configuring a Pending Broadcast

A pending broadcast may be configured by chaining before it's awaited:

rust
use turbo::{channel, stream};

stream::append("messages", "Hi")
    .broadcast_to("room.1")
    .to(channel::presence("room.1")) // other channels instead
    .action("prepend")               // another action
    .target("messages")              // another target, or `.targets(".messages")`
    .attr("data-kind", "chat")       // an attribute on the <turbo-stream>
    .to_others()                     // not to the browser that sent the request
    .cancel_if(is_draft)             // don't send it at all
    .await?;
Method Effect
to(channels) Broadcasts on these channels instead.
action(name) Changes the stream's action.
target(target), targets(selector) Changes the element or elements the stream changes.
content(content) Changes what the stream puts on the page.
attr(name, value) Adds an attribute to the <turbo-stream> element.
morph(), preserve_scroll() Morphs instead of replacing, and keeps the scroll position on a refresh.
to_others() Leaves out the browser that sent the current request, by its X-Socket-Id.
now() Publishes right away, instead of through a queued job after the transaction commits.
cancel(), cancel_if(condition) Doesn't send the broadcast.
request_id(id) Sets a refresh stream's request-id.

Broadcasting Turbo Streams to Other Users Only

As mentioned earlier, the user who made the change usually gets their update over HTTP, and the broadcast goes to everyone else. to_others leaves out the browser that sent the request:

rust
use laravel::model::create;
use laravel::prelude::*;
use laravel::validation::ValidRequest;
use turbo::{RequestExt, stream};

pub async fn store(post: Post, input: ValidRequest<StoreComment>) -> laravel::Result<Response> {
    let (form, request) = input.into_parts();
    let comment = create!(Comment { post_id: post.id, body: form.body }).await?;
    let stream = stream::append("comments", view("comments.partials.comment", data! { comment }));

    stream.clone().broadcast_to(&post).to_others().await?;

    if request.wants_turbo_stream() {
        return Ok(stream.into_response());
    }

    Ok(redirect!(posts::show, post.id).into_response())
}

Echo adds the browser's socket ID to Turbo's requests in the X-Socket-Id header, as long as Turbo loads first, which is why the entry file imports @hotwired/turbo before ./echo. Broadcasts sent outside a request, such as from a queued job, go to everyone.

Broadcasting Page Refreshes

Instead of describing each change with a stream, a broadcast may tell pages to refresh themselves. With morphing on, the refresh feels like a live update:

rust
use turbo::stream;

stream::refresh().broadcast_to(&post).await?;

A refresh broadcast carries the current request's X-Turbo-Request-Id as its request-id, so the page that made the change, which already shows it, doesn't refresh again. Turbo also debounces refreshes that arrive close together. request_id(None::<String>) refreshes every page, including the one that made the change.

Broadcasting Model Changes

Most broadcasts follow a model's changes: a new comment appears, an edited one updates, a deleted one goes away. #[turbo::broadcasts] sends those streams when the model is created, updated or deleted, with laravel's model events. Write it above #[model]:

rust
use laravel::model::model;

#[turbo::broadcasts(to = Post)]
#[model]
pub struct Comment {
    pub id: i64,
    pub post_id: i64,
    pub body: String,
}
Event Stream Listener
Created append the comments.partials.comment partial into #comments queued
Updated replace #comment_7 with the partial queued
Deleted remove #comment_7 after the commit

to = Post broadcasts on the post's channel, posts.{post_id}, so the post's page hears about its comments with turbo_stream_from(post). Without to, a model broadcasts on its own channel. The partial gets the model as comment, its morph name, and since queued listeners reload the model, the broadcast shows the latest row.

The attribute also identifies the model for templates, so it's the only attribute a broadcasting model needs.

Options

Option Effect
to = Parent Broadcasts on the parent's channel, from the {parent}_id column.
foreign_key = "author_id" Names the column to reads, when it isn't {parent}_id.
partial = "comments.partials.card" Renders another partial.
target = "post_comments" The element new models go in, instead of the table's name.
action = prepend Puts new models at the start of the target.
refresh Sends a refresh stream on every change instead.
public, presence The channel's kind, instead of private.
manual Doesn't broadcast on model events. See Broadcasting by hand.

For example, a board that shows its newest notes first, to anyone:

rust
use laravel::model::model;

#[turbo::broadcasts(to = Board, partial = "notes.partials.card", action = prepend, public)]
#[model]
pub struct Note {
    pub id: i64,
    pub board_id: i64,
    pub body: String,
}

To skip broadcasting a single change, use laravel's quiet writes: .quietly() on a create! or update!, delete_quietly(), or model::without_events.

Broadcasting by Hand

Models with #[turbo::broadcasts] may also broadcast their own streams, with the attribute's options, through the Broadcasting trait. Each method returns the same pending broadcast as broadcast_to, so it chains the same way:

rust
use turbo::Broadcasting;

comment.broadcast_append().to_others().await?;
comment.broadcast_prepend().await?;
comment.broadcast_before("comment_3").await?;
comment.broadcast_after("comment_3").await?;
comment.broadcast_replace().morph().await?;
comment.broadcast_update().await?;
comment.broadcast_remove().await?;
comment.broadcast_refresh().await?;
comment.broadcast_action("highlight").attr("color", "yellow").await?;
comment.broadcast_append().to(&other_post).cancel_if(comment.draft).await?;

broadcast_action sends a custom action. Like broadcast_append and broadcast_prepend, it targets the table's element for append and prepend, and the model's DOM ID otherwise.

Add manual to broadcast only by hand. The automatic broadcasts stop, and the other options still apply to the methods:

rust
use laravel::model::model;

#[turbo::broadcasts(to = Post, manual)]
#[model]
pub struct Comment {
    pub id: i64,
    pub post_id: i64,
    pub body: String,
}