livewire·rust

Getting started

Four files: a dependency, a provider line, a component, and a page that mounts it.

counter.rs
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.counter")]
pub struct Counter {
    pub count: i32,
    #[livewire(locked)]
    pub id: String,
}

#[component]
impl Counter {
    pub fn increment(&mut self) {
        self.count += 1;
    }
}
Live exampleopen ↗

The frame runs the deployed lab; each button below is a round trip that posts a signed snapshot and morphs the HTML.

Requirements

Serving the application locally? Laser Stack gives a Laravel Rust project a trusted name and certificate, and proxies the vhost to the server the project runs — see its documentation.

A deployed example plays through every section of this guide: the feature lab ↗.

Install

cargo add livewire-rust
# with model references and pagination, plus one database driver:
cargo add livewire-rust --features database-sqlite

Or, in Cargo.toml by hand:

[dependencies]
livewire-rust = "0.1"
# or, with model references and pagination:
# livewire-rust = { version = "0.1", features = ["database-sqlite"] }

The crate is livewire-rust; the library it provides is livewire, so the first line of a file that uses it is use livewire::…. The manifest pins the framework at =0.2.0.

Register the provider

The application adds one provider. Its closure registers the components and any custom behaviour; it runs once, when the provider registers.

use livewire::LivewireServiceProvider;

Application::configure().with_providers(|providers| {
    providers.add(LivewireServiceProvider::new(
        |components: &mut livewire::ComponentRegistry| {
            components
                .register::<crate::livewire::counter::Counter>("counter")
                .expect("the counter component is registered once");
        },
    ));
})

Startup is strict. The provider boots only with a valid application encryption key, because that key signs every snapshot, and it reports a missing component directory instead of rendering an empty site later.

Write a component

A component is a struct plus an annotated impl. The derive maps fields to their wire roles; the impl declares the actions.

// src/livewire/counter.rs
use livewire::{LivewireComponent, component};

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.counter")]
pub struct Counter {
    pub count: i32,
    pub step: i32,
    #[livewire(validate(required, max_length(10)))]
    pub label: String,
    #[livewire(locked)]
    pub id: String,
}

#[livewire::component]
impl Counter {
    pub fn increment(&mut self) {
        self.count += self.step;
    }
}

The view is a Jinja file beside the other views, named after the component. Its markup must have one root element, which the runtime annotates with wire:id, wire:name, the snapshot, and the effects.

<!-- resources/views/livewire/counter.livewire -->
<div>
  <h2 data-count>{{ count }}</h2>
  <input wire:model.live="step" type="number" min="1">
  <button wire:click="increment">Add</button>
</div>

Mount it from a page

An ordinary page template embeds the component with livewire(name, props, key):

<!-- resources/views/livewire/counter-page.html -->
{% extends "layouts.app" %}
{% block content %}
  {{ livewire("counter", {"count": 5}, "counter-main") }}
{% endblock %}
// src/routes/web.rs
pub fn routes(route: &mut Router) {
    route.get("/livewire/counter", livewire::counter);
}

The handler for that route returns the page view. The styles and scripts inject themselves into HTML responses when inject_assets is on; the page may also call {{ livewire_styles() }} and {{ livewire_scripts() }} itself, and then injection leaves it alone.

Or render the component as the page

A page component has no surrounding template: its own view extends the layout, and the route answers with its markup.

// the page's view: resources/views/livewire/post-browser.livewire
{% extends "layouts.app" %}
{% block content %}<h1>Posts</h1>{% endblock %}
// the route
pub async fn posts(registry: Inject<Arc<ComponentRegistry>>) -> Response {
    let html = livewire::page::render_page(&registry, "post-browser", Params::default())
        .expect("the page mounts");
    Response::html(html)
}

Route parameters and route guards belong to the routing layer; pass what the component needs as props. See Pages & guards.

Commands

laravel make:livewire counter            # module and .livewire view
laravel make:livewire pages.posts --mfc  # module beside a view file
laravel livewire:config                  # print the resolved configuration
laravel livewire:publish --assets        # serve the runtime from public/

livewire:make is an alias of make:livewire. The rest are in the reference.

Test it

The crate ships the same path the browser takes: an application test renders the page, reads the snapshot out of the HTML, and posts an update to the real endpoint.

#[laravel::test]
async fn a_click_increments_the_counter(app: Application) {
    let page = parse(&app.get("/livewire/counter").await.text());

    let response = app
        .post(&page.update_uri)
        .header("x-livewire", "1")
        .json(update(&page, &page.snapshot,
             json!({"step": 2}),
             json!([{"method": "increment", "params": [], "metadata": {}}])))
        .await;

    response.assert_ok();
}

Single components can also be driven directly through the testing harness, which mounts, runs an action, and asserts on the result: assert_set, assert_see, assert_dont_see, assert_dispatched, assert_redirected_to.

Configuration

Every setting has the upstream default. An application overrides any of them with a LivewireConfig section in its own configuration; without one, LivewireConfig::of returns the defaults. The full table is in the reference.