Tutorial: a searchable customer list
Build a list page: search as you type, show the number of matches, delete rows, and only ever see or delete your own customers.
The finished result is one model, one Linker component, one handler and one template, with no JS.
1. Plan: who does what
| Requirement | Handled by |
|---|---|
| The search keyword | Kept in Linker's server state (Stateful) |
| The number of matches | Linker returns data → data-state-text |
| The list | Linker returns dom.repeat, sending only JSON; the first page of data is embedded in the page |
| The search box keeps its text after a redraw | Client state (data-state-bind) |
| Deleting | A Linker method + policy + data-linker-confirm-danger |
Why the list doesn't use render fragments
The PHP version uses render.fragment here to have a controller redraw the list. Rust fragment functions can't see the logged-in user (RenderInput has only method, params, target and url), so they can't list only "your" customers. Linker has context.user, so the natural way is for Linker to query the data and send it with dom.repeat. Every row has the same structure, which is exactly what dom.repeat is good at.
2. Migration and model
laravel make:migration create_customers_table// database/migrations/2026_12_02_000000_create_customers_table.rs
use laravel::db::AnyTransaction;
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.schema()
.create("customers", |table| {
table.id();
table.foreign_id("user_id").constrained().cascade_on_delete();
table.string("name");
table.string("email");
table.timestamps();
table.index(["user_id", "name"]);
})
.await
}The model and policy go in the same file:
// src/models/customer.rs
use laravel::auth::policy;
use laravel::model::model;
use laravel::time::Timestamp;
use crate::models::User;
#[model]
pub struct Customer {
pub id: i64,
pub user_id: i64,
pub name: String,
pub email: String,
pub created_at: Timestamp,
pub updated_at: Timestamp,
}
pub struct CustomerPolicy;
#[policy]
impl CustomerPolicy {
pub fn delete(user: &User, customer: &Customer) -> bool {
user.id == customer.user_id
}
}Add mod customer; and pub use customer::{Customer, CustomerPolicy}; to src/models/mod.rs, then run laravel migrate.
3. The Linker component
// src/cg/customer.rs
use cg_component::runtime::linker::{Action, Args, LinkerComponent, LinkerContext, LinkerResponse};
use laravel::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::models::{Customer, CustomerPolicy, User};
#[derive(Default, Serialize, Deserialize)]
pub struct CustomerList {
keyword: String,
}
impl LinkerComponent for CustomerList {
const ALIAS: &'static str = "customerList";
const METHODS: &'static [&'static str] = &["search", "delete"];
const ALLOWS_REFERER_URLS: &'static [&'static str] = &["/customers"];
async fn call(&mut self, context: &LinkerContext, method: &str, args: Args) -> laravel::Result<LinkerResponse> {
let user = current_user(context).await?;
match method {
"search" => {
let keyword = args.get("keyword").and_then(Value::as_str).unwrap_or_default().trim();
if keyword.chars().count() > 64 {
return Ok(LinkerResponse::validation([("keyword", "The keyword can be at most 64 characters.")]));
}
self.keyword = keyword.to_owned();
}
"delete" => {
let Some(id) = args.get("id").and_then(Value::as_i64) else {
return Ok(LinkerResponse::validation([("id", "The customer id is missing.")]));
};
let customer = Customer::find_or_fail(id).await?;
user.authorize(CustomerPolicy::delete, &customer).await?;
customer.delete().await?;
}
_ => unreachable!("METHODS lists every method"),
}
let rows = rows(&user, &self.keyword).await?;
let response = LinkerResponse::ok()
.data("matchCount", rows.len())
.then(Action::new("dom.repeat", json!({ "ref": "customers", "items": rows })).map_err(laravel::Error::msg)?);
Ok(if method == "delete" {
response.then(Action::toast("success", "Deleted"))
} else {
response
})
}
}
/// Shared by the seed and dom.repeat, so both always have the same shape.
pub async fn rows(user: &User, keyword: &str) -> laravel::Result<Vec<Value>> {
let mut query = Customer::query().filter(Customer::user_id.eq(user.id));
if !keyword.is_empty() {
query = query.filter(Customer::name.contains(keyword));
}
let customers = query.order_by(Customer::id.desc()).limit(50).get().await?;
Ok(customers
.into_iter()
.map(|c| json!({ "id": c.id, "name": c.name, "email": c.email }))
.collect())
}
async fn current_user(context: &LinkerContext) -> laravel::Result<User> {
let id: i64 = context.user.parse()?;
User::find_or_fail(id).await
}Notes:
context.useris the logged-in user's id (as text). To use a policy, load theUser.delete'sidis input the user can change:find_or_failreturns 404 when it isn't found → the browser getsservice"找不到這筆資料。" (not found); a failedauthorizereturns 403 →policy. Just propagate errors with?, andcalltranslates them into a kind the browser understands, based on the HTTP status.- It only queries rows where
user_id = the logged-in user, so other people's customers never appear in the list. - After a delete it re-queries with the
keywordthe server remembered, so the browser doesn't have to send it again. Customer::name.contains(..)escapes%and_automatically, so user input never becomes a wildcard.ALLOWS_REFERER_URLSonly allows calls from/customers(it narrows the exposure; it isn't authorization).
To register it: add pub mod customer; and pub use customer::CustomerList; to src/cg/mod.rs, and call linker::register::<CustomerList>() in register().
4. The page handler
// src/http/handlers/customers.rs
use cg_component::runtime::{self, Allow, linker};
use laravel::prelude::*;
use laravel::view::{Html, View};
use crate::cg::{CustomerList, customer};
use crate::models::User;
pub async fn index(user: Authenticated<User>) -> laravel::Result<View> {
let mount = linker::mount::<CustomerList, User>(&user, linker::Args::new()).await?;
let panel = runtime::render_object("customerPanel", &[Allow::StateRead, Allow::StateWrite]);
let rows = customer::rows(&user, "").await?;
Ok(view("customers.index", data! { total => rows.len() })
.with_html("panel_attrs", Html::raw(mount.html() + &panel.render(&[])))
.with_html("seed", Html::raw(seed("customers", &rows))))
}
/// `<script type="application/json" data-linker-ref-seed>`: JSON that can't close its tag.
fn seed(name: &str, items: &impl serde::Serialize) -> String {
let json = serde_json::to_string(items)
.unwrap_or_else(|_| "null".into())
.replace('<', "\\u003c")
.replace('>', "\\u003e")
.replace('&', "\\u0026");
format!(
r#"<script type="application/json" data-linker-ref-seed="{}">{json}</script>"#,
cg_component::escape(name)
)
}Add route.get("/customers", customers::index); to src/routes/web.rs.
- The seed is a hand-written version of PHP's
@linkerRefSeed: the first page of data is embedded in the page, and the browser applies it once at boot, saving a round trip.<,>and&become escapes like<, so a</script>in the data can't close the tag. - The render object grants
StateRead(data-state-text) andStateWrite(data-state-bind,data-state-init, and Linker writingdata). It doesn't needRender, because there are no render fragments.
5. The template
{% extends "layouts/site.html" %}
{% block title %}Customers{% endblock %}
{% block content %}
<main class="mx-auto grid max-w-3xl gap-4 px-6 py-12"{{ panel_attrs }} data-state-init="keyword=">
<input type="search" name="keyword" placeholder="Search customers"
data-state-bind="keyword"
data-linker-call="search"
data-linker-on="input"
data-linker-debounce="400"
data-linker-args="keyword">
<p><span data-state-text="matchCount">{{ total }}</span> matches</p>
<table>
<tbody>
<tr class="hidden" data-linker-ref-dom="customers">
<td>%name%</td>
<td>%email%</td>
<td>
<button type="button"
data-linker-call="delete"
data-linker-args='{"id": %id%}'
data-linker-confirm="This can't be undone"
data-linker-confirm-danger>Delete</button>
</td>
</tr>
<tr data-linker-ref-empty="customers"{% if total > 0 %} class="hidden"{% endif %}>
<td colspan="3">No matching customers</td>
</tr>
</tbody>
</table>
{{ seed }}
</main>
{% endblock %}- The mount point and render object are on the outermost element, and every
data-linker-*anddata-linker-ref-*is inside it. - The hidden reference row (
data-linker-ref-dom) is never shown;dom.repeatcopies it and fills placeholders like%name%withtextContent. A<b>in a customer name is just text. - The empty-state row gets
hiddenup front, based on thetotalthe server computed, so it doesn't flash. - The
data-linker-call="delete"in copied rows is bound automatically after they're inserted (a rescan aftercg:rendered).
The full rules for reference rows and placeholders are in dom.repeat.
6. Check it
Open the page and DevTools:
- Type → Network shows a single
linkerrequest (debounced 400ms), and the response containsdom.repeatandmatchCount. - Delete → the confirmation needs two clicks → a toast → the list and count update.
- Call
deletewith someone else's customer id →{"ok": false, "kind": "policy"}.
Turn these into a test (tests/customers.rs):
#[laravel::test]
async fn customers_can_only_delete_their_own(app: Application) -> laravel::Result<()> {
let owner = create!(User { name: "A", email: "a@x.test", password: "password" }).await?;
let other = create!(User { name: "B", email: "b@x.test", password: "password" }).await?;
let mine = create!(Customer { user_id: owner.id, name: "Acme", email: "a@acme.test" }).await?;
let theirs = create!(Customer { user_id: other.id, name: "Other", email: "o@x.test" }).await?;
let page = app.get("/customers").acting_as(&owner).await;
let instance = attribute(&page.text(), r#"data-linker="customerList""#, "data-linker-instance");
let call = |rev: u64, method: &str, args: serde_json::Value| {
json!({ "component": "customerList", "instance": instance, "rev": rev, "method": method, "args": args })
};
app.post(endpoints::linker_url()).acting_as(&owner).json(call(0, "delete", json!({ "id": theirs.id }))).await
.assert_json(json!({ "ok": false, "kind": "policy" }));
app.post(endpoints::linker_url()).acting_as(&owner).json(call(0, "delete", json!({ "id": mine.id }))).await
.assert_json(json!({ "ok": true, "data": { "matchCount": 0 }, "rev": 1 }));
Ok(())
}attribute is the small function in tests/runtime.rs that reads an attribute value from HTML; copy it over.
7. Variant: with render fragments
If the list doesn't depend on the user (a public product catalog, say), or rows differ a lot in structure, you can go back to the PHP approach: register a fragment customers.results, and have Linker return Action::render_fragment("#results", "customers.results", json!({ "keyword": keyword })). The fragment function must validate params itself, and can't assume who is calling. See Asking the server for fragments.