Models, pagination, and computed properties
A row never crosses the wire: the snapshot carries a key, and the server fetches the row before it renders. Pagination and computed values follow the same rule: the browser holds a reference, the server recomputes.
use livewire::LivewireComponent;
use livewire::component;
use livewire::models::ModelRef;
use crate::models::Post;
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.post-card")]
pub struct PostCard {
#[livewire(model)]
pub post: ModelRef<Post>,
}
#[component]
impl PostCard {
pub fn load(&mut self, id: i64) {
self.post = ModelRef::referencing(id);
}
}The snapshot holds the row key, never the row; load another post and the server fetches it before rendering.
What crosses the wire
Most fields are plain JSON. A field whose JSON form cannot be read back without a type tag goes through a synthesizer: its value sits in data under the field's name, and its metadata sits in data.__meta__ under the same name. The metadata's s key names the synthesizer.
The runtime synthesizer table always holds five keys: arr, std, str, int, and float. An application adds its own with registry.register_synth::<S>() or register_synth_key. The registry rejects a second registration under the same key.
Metadata comes from the verified snapshot, never from the update. The key is read from the checksum-protected previous snapshot, and the synthesizer is the one the derive named for the field's Rust type. A browser cannot choose which synthesizer reads a field, and no type is ever instantiated from a name in the input.
Model references
The models module sits behind the crate's database feature, together with the framework's database dependency. Enable one driver beside it, for example database-sqlite.
use livewire::LivewireComponent;
use livewire::component;
use livewire::models::ModelRef;
use crate::models::Post;
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.post-card")]
pub struct PostCard {
#[livewire(model)]
pub post: ModelRef<Post>,
}
#[component]
impl PostCard {
pub fn load(&mut self, id: i64) {
self.post = ModelRef::referencing(id);
}
}
#[livewire(model)] requires a ModelRef<T> field; the derive rejects any other type, and rejects combining it with synth, session, or skip. The model type comes from the field, so the class name in a snapshot is always the field's own type, never a name the input chose.
ModelRef<T> keeps a key and an optional row:
| Method | Meaning |
|---|---|
ModelRef::referencing(key) | A reference whose row is fetched on the next update |
ModelRef::of(row) | A reference to a row the caller already holds |
get() | The row, when it has been fetched |
unresolved() | The key still to fetch, or None when the row is held |
key() | The key, fetched or not |
ModelRef::<T>::class() | The model's morph name, which the wire metadata carries |
found(Option<T>) | Takes the fetched row, or fails with ModelNotFound |
The wire form of a reference
The key is the field's value, and the metadata rides beside it in data.__meta__. The row is not sent.
"data": {
"post": 12,
"__meta__": {
"post": { "s": "mdl", "class": "post" }
}
}
An empty reference crosses as null. Hydration checks the class against the field's type; a reference to another class is a hydration failure (419).
When the row is fetched
Fetching is part of the update pipeline, not of hydration. ModelRef only writes and reads the reference; the derive generates one async fetch per model field, and the pipeline calls it twice.
- After the snapshot hydrates the fields and the
hydratelifecycle runs, beforeupdating,updated, and any action. - After the actions run, before the render, for references still unresolved. An action or a
$set-style update that writes a new key is fetched before that same response renders.
Mount does not fetch. mount is synchronous, and the row is resolved in the next update. A reference passed to the mount is therefore resolved on the first update, not on the first render.
A key that names no row is a 404: Unable to find the [post] model for the reference [9999999]. The reference keeps the key it asked for, so the message can name it.
What is not there
- No bare model field. A component cannot hold a
Postdirectly. The field must beModelRef<Post>; anOption<ModelRef<T>>orVec<ModelRef<T>>is refused at compile time. Write an empty reference asModelRef::default(). - No collection or lazy-proxy synthesizer. There is no
Collectiontype, no lazy proxy, and no deferred model resolution: the two pipeline passes above are the whole story. - No
mdlentry in the runtime table. The derive namesModelRef<T>itself, so nothing resolves a model type from input.registry.has_synth("mdl")is false.
Pagination
Paging uses the framework's paginator. A component keeps the page number, the last page, and the rows it needs; the paginator itself lives for one request:
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.post-list")]
pub struct PostList {
#[livewire(url(as = "page", use = "push", always_show = true))]
pub page: i64,
pub posts: Vec<Row>,
pub last_page: i64,
}
#[component]
impl PostList {
pub async fn go(&mut self, page: i64) {
self.page = page.clamp(1, self.last_page.max(1));
self.load().await.ok();
}
pub async fn next(&mut self) {
self.go(self.page + 1).await;
}
pub async fn previous(&mut self) {
self.go(self.page - 1).await;
}
async fn load(&mut self) -> laravel::Result<()> {
let paginator = Post::query()
.order_by(Post::id.desc())
.paginate(PER_PAGE)
.page(self.page as u64)
.await?;
self.posts = paginator
.items()
.iter()
.map(|post| Row { id: post.id, title: post.title.clone() })
.collect();
self.last_page = paginator.last_page() as i64;
Ok(())
}
}
The page number is a query-string field, so its URL descriptor is sent at mount and the browser keeps ?page= in the address as it changes. The initial page comes from the page that mounts the component: the route handler awaits the first paginator and passes posts, last_page, and page as props.
A page past the end is clamped, not empty. go(99) on a two-page list answers with page 2.
There is no WithPagination trait. Actions are inherent methods that #[component] publishes, so a trait cannot add nextPage, previousPage, gotoPage, or resetPage to the browser's reach. Declare each action yourself, as above. The pagination_theme setting exists but the port ships no paginator views; write the controls in the component's template.
Computed properties
Mark a method with #[livewire(computed)]. The template reads it like a field, and it is never stored on the wire:
/// Twice the count, computed for the template rather than stored on the wire.
#[livewire(computed)]
pub fn doubled(&self) -> i32 {
self.count * 2
}
<p>Doubled: <strong>{{ doubled }}</strong></p>
The value is memoized for the rest of the request, keyed by component ID and property name, so a template that prints it twice computes it once. It is added to the render data only; data in the snapshot carries fields, not computed values, and the next request computes it again.
A computed method takes &self, no arguments, and is not an action. A call naming it is an unknown method (419).
Caching and persistence are refused at compile time. #[livewire(computed(cache = true))], persist, seconds, key, and tags produce: computed(..) options are not implemented: write #[livewire(computed)]. There are no cache keys, no persisted per-component values, and no expiry to configure.
Nothing is deferred automatically
The port has no lazy phase for models, paginators, or computed values. Deferral is one class option: #[component(lazy)] or #[component(defer)] renders a placeholder with wire:init="__lazyLoad", and the update that follows renders the real view. Async work belongs in an action, where the pipeline can await it; the mount and the render stay synchronous.