# laravel-rust-admin
An admin panel for [Laravel for Rust](https://laravel.com/rust) applications. Describe your models as resources, add one service provider, and your application serves a back office at `/admin`.
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/shots/orders-dark.webp">
<img src="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/shots/orders-light.webp" alt="The orders table of the demo: tabs with counts, a search box, filter chips, and a row for each order">
</picture>
Each resource gets a table with search, filters, tabs, sorting, pagination, and CSV export, and forms that create and edit records through your own `#[laravel::input]` structs, so your validation rules decide what the panel can save. You can add actions on one record or on many, a dashboard of stats, charts, and tables, and policies for who may do what. A command palette (⌘K) searches every resource.
The frontend is built into the crate. Your application needs no Node toolchain, and the panel loads nothing from other hosts.
<table>
<tr>
<td width="50%">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/readme/form-dark.webp">
<img src="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/readme/form-light.webp" alt="The form for a new customer, with a validation message under the email, the plan and the country">
</picture>
</td>
<td width="50%">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/readme/action-dark.webp">
<img src="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/readme/action-light.webp" alt="A dialog that asks for a reason before it refunds an order">
</picture>
</td>
</tr>
<tr>
<td><b>Forms.</b> Your input structs decide what can be saved, and their messages show under the fields.</td>
<td><b>Actions.</b> On one record or on many, with a confirmation and fields of their own.</td>
</tr>
<tr>
<td width="50%">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/readme/dashboard-dark.webp">
<img src="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/readme/dashboard-light.webp" alt="The dashboard of the demo: four stats, a chart of orders per day, and a chart of orders by status">
</picture>
</td>
<td width="50%">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/readme/palette-dark.webp">
<img src="https://raw.githubusercontent.com/n7olkachev/laravel-rust-admin/main/docs/readme/palette-light.webp" alt="The command palette over the orders table, with two customers found for the search “tana”">
</picture>
</td>
</tr>
<tr>
<td><b>Dashboard.</b> Each stat, chart, and table is an async function of yours.</td>
<td><b>⌘K.</b> One search across every resource the user may see.</td>
</tr>
</table>
The panel has a light and a dark appearance, and these screenshots show the one that matches yours. For a tour with more of them, and the code behind each, open [`docs/index.html`](https://github.com/n7olkachev/laravel-rust-admin/blob/main/docs/index.html) from a checkout.
> [!NOTE]
> This is early work, and the API will change. The panel is built against `laravel-rust` 0.1 and has only been run on SQLite so far.
## Try the demo
The repository includes a small shop's back office with orders, customers, and products:
```shell
git clone https://github.com/n7olkachev/laravel-rust-admin
cd laravel-rust-admin
cargo run -p laravel-rust-admin-demo
```
Then open <http://127.0.0.1:8000/admin>. Set `SERVER_PORT` to serve on another port. The demo keeps its data in an in-memory database that it creates and fills on every start.
## Installation
```shell
cargo add laravel-rust-admin
```
The panel needs Rust 1.99 or newer, as Laravel for Rust does, and uses whichever database driver your application enables on `laravel-rust`.
## Quick start
The quickest resource is a derive on a model. Its table and its form come from the model's fields:
```rust
use laravel::model::model;
use laravel::time::Timestamp;
use laravel_rust_admin::AdminResource;
#[model]
#[derive(AdminResource)]
#[admin(icon = "users", create = StoreCustomer, update = StoreCustomer)]
pub struct Customer {
pub id: i64,
#[admin(column(avatar, searchable, sortable, description = "email"))]
pub name: String,
#[admin(column(skip, searchable))]
pub email: String,
#[admin(column(badge), filter(select = ["free", "pro"]), field(options = ["free", "pro"]))]
pub plan: Plan,
#[admin(filter(boolean), field(default = true))]
pub active: bool,
pub created_at: Timestamp,
pub updated_at: Timestamp,
}
#[laravel::input(fills = Customer)]
#[validate(authenticated)]
pub struct StoreCustomer {
#[validate(required, max_length(120))]
pub name: String,
#[transform(lowercase)]
#[validate(required, email)]
pub email: String,
pub plan: Plan,
pub active: bool,
}
```
The panel only creates and updates records through the input structs you name. Their rules run on every save, their messages appear under the form's fields, and a field the struct doesn't declare can't be written, whatever the browser sends. A resource without `create` or `update` is read-only.
Then add the panel to your providers in `src/app.rs`, and say who may enter:
```rust
use laravel::Application;
use laravel::auth::Authenticate;
use laravel::http::Request;
use laravel_rust_admin::AdminPanel;
async fn admins_only(request: &Request) -> laravel::Result<bool> {
Ok(request.user::<User>().await?.is_some_and(|user| user.is_admin))
}
Application::configure()
.with_providers(|providers| {
providers.add(
AdminPanel::new()
.brand("Acme")
.middleware(Authenticate)
.authorize(admins_only)
.resource::<Customer>(),
);
})
```
The derive's documentation lists every `#[admin(..)]` option, and what the derive works out from a field's type and name.
## Who may use the panel
A panel is only as safe as the answer to "who may enter", so the panel insists on one:
- `middleware(..)` attaches middleware to every panel route, such as `Authenticate`.
- `authorize(..)` takes an `async fn(&Request) -> laravel::Result<bool>` that runs before every panel request, after the middleware. Returning `false` responds with a `403`.
A panel with neither would be open to anyone who finds its URL. Such a panel only answers in the `local` and `testing` environments. Everywhere else it responds with a `403`, and logs a warning at startup, until you add one of the two.
`user_resolver(..)` tells the panel who is using it, for the user menu and the dashboard's greeting. `logout_url(..)` adds "Log out" to that menu. The panel sends it a `POST` with the CSRF token.
Every write the panel makes carries the session's CSRF token, so the panel works with Laravel's `PreventRequestForgery` middleware as it is.
## Resources by hand
Implement `AdminResource` yourself, usually on a unit struct, when a resource needs more than the derive offers. This is the demo's orders resource, shortened:
```rust
use laravel::db::Builder;
use laravel::http::Request;
use laravel::model::update;
use laravel_rust_admin::prelude::*;
pub struct OrderResource;
impl AdminResource for OrderResource {
type Model = Order;
type CreateInput = ReadOnly; // Orders come from the storefront.
type UpdateInput = EditOrder;
fn slug() -> &'static str { "orders" }
fn label() -> &'static str { "Order" }
fn plural_label() -> &'static str { "Orders" }
fn icon() -> &'static str { "shopping-bag" }
fn navigation_group() -> Option<&'static str> { Some("Sales") }
async fn query(_request: &Request, query: Builder<Order>) -> laravel::Result<Builder<Order>> {
Ok(query.with(Order::customer))
}
fn table(table: TableBuilder<Order>) -> TableBuilder<Order> {
table
.column(Column::text("number").label("Order").searchable().sortable().copyable())
.column(Column::avatar("customer.name").label("Customer").description_column("customer.email"))
.column(Column::badge("status").sortable().color("paid", BadgeColor::Sky).color("shipped", BadgeColor::Emerald))
.column(Column::currency("total", "USD").sortable())
.column(Column::relative_time("placed_at").label("Placed").sortable())
.tab(TableTab::all("All orders"))
.tab(TableTab::new("pending", "Pending", |query| query.filter(Order::status.eq(OrderStatus::Pending))))
.filter(Filter::select("status").options([("pending", "Pending"), ("paid", "Paid"), ("shipped", "Shipped")]))
.filter(Filter::date_range("placed_at").label("Placed"))
.default_sort("placed_at", SortDirection::Desc)
.action(
RowAction::new("refund", "Refund", |context, mut order: Order| async move {
let reason = context.string("reason").unwrap_or_default();
update!(order { status: OrderStatus::Refunded, note: Some(format!("Refunded: {reason}")) }).await?;
Ok(ActionOutcome::message(format!("Order {} was refunded.", order.number)))
})
.destructive()
.available_when(|order: &Order| order.status == OrderStatus::Paid)
.confirm("Refund this order?", "The customer gets the full amount back.")
.field(Field::textarea("reason").required()),
)
}
fn form(form: FormBuilder) -> FormBuilder {
form.section(
FormSection::new("Fulfilment")
.field(Field::select("status").required().options([("pending", "Pending"), ("paid", "Paid")]))
.field(Field::textarea("note").nullable()),
)
}
async fn authorize_delete(request: &Request, order: &Order) -> laravel::Result<bool> {
request.can(OrderPolicy::delete, order).await
}
}
```
### The table
A column's name is a field of the serialized model. `Column` has a constructor for each way to show a value: `text`, `badge`, `boolean`, `number`, `currency`, `datetime`, `date`, `relative_time`, `avatar`, `tags`, and `json`.
- **Relationships.** Load a relationship in `query`, and name a column with a dotted path, such as `customer.name`. The database can't sort or search by such a column, and the panel refuses to start if you ask it to.
- **Search.** The table's search box, and the command palette, look in the `searchable()` columns and in the columns you pass to `search_by([..])`, which don't have to be shown.
- **Filters.** `Filter::select`, `Filter::boolean`, `Filter::date_range`, and `Filter::text` appear as chips above the table. Each can replace how it narrows the query with `.query(..)`.
- **Tabs.** A `TableTab` narrows the table to some of its records, and shows how many there are.
- **Export.** "Export" downloads every record that matches the current search, filters, and tab as CSV. The export is streamed, so it may be of any size, and cells that a spreadsheet would run as formulas are neutralized.
The table's state lives in the URL, so a filtered view can be bookmarked or shared.
### The form
`Field` has a constructor for each kind of input: `text`, `email`, `url`, `password`, `textarea`, `number`, `decimal`, `select`, `radio`, `toggle`, `checkbox`, `date`, `datetime`, `civil_datetime`, `tags`, `json`, and `readonly`. Group fields into a `FormSection` to give them a heading and a layout of one to three columns.
The form is only the form. What gets saved is decided by the resource's `CreateInput` and `UpdateInput`.
### Actions
A `RowAction` runs on one record and a `BulkAction` on every selected record. An action can ask for confirmation, and can collect fields before it runs, which its handler reads from the `ActionContext`. The handler returns an `ActionOutcome` with the message to show. An error's message is shown instead.
`available_when(..)` says which records a row action applies to, such as "ship" only for an order that is paid. The panel leaves the action out of every other record's menu, and refuses to run it on them.
### Authorization
Every `authorize_*` method of `AdminResource` allows everything until you override it: `authorize_view_any`, `authorize_view`, `authorize_create`, `authorize_update`, `authorize_delete`, and `authorize_action`. Each receives the request, so it can check a policy with `request.can(..)`. The panel enforces them on the server, and uses their answers to hide what the user may not do.
To limit which records a user sees at all, such as their own team's, narrow `query`. A record the query leaves out doesn't exist as far as the panel is concerned: it's in no table, search, or export, and its URL responds with a `404`.
## The dashboard
A widget is an async function that returns a `StatWidget`, a `ChartWidget`, or a `TableWidget`. It runs each time the dashboard loads:
```rust
async fn open_orders() -> laravel::Result<StatWidget> {
let count = Order::query().filter(Order::status.eq(OrderStatus::Pending)).count().await?;
Ok(StatWidget::new("open_orders", "Open orders", count.to_string())
.trend("+12%", TrendDirection::Up)
.href("/resources/orders?tab=pending"))
}
AdminPanel::new().widget_fn(open_orders)
```
`widget_for_request` takes a function of the request instead, for a widget that shows the logged-in user's own numbers. A panel without widgets shows a count of each resource's records.
## Configuration
| `path("/admin")` | `ADMIN_PATH` | Where the panel is mounted |
| `brand("Acme")` | `ADMIN_BRAND` | The name in the sidebar and the page title |
| `subtitle("Back office")` | | A line under the brand |
| `accent(AccentColor::Indigo)` | | The color of primary buttons and checked controls |
| `logout_url("/logout")` | | The "Log out" item of the user menu |
The panel follows the operating system's light or dark appearance until the user picks one from the user menu.
## How it's put together
The crate serves a single-page app from files embedded in the binary, and a JSON API under `{path}/api` that the app talks to. The app's types mirror the Rust types in `src/protocol.rs` by hand for now. They are meant to be generated by `laravel-rust-typescript-bridge`.
The panel's page works with a Content Security Policy: its inline script carries the nonce from `laravel::view::csp_nonce()`. Its font, Inter, ships with the crate, and `dist/THIRD-PARTY-LICENSES.txt` holds the licenses of everything in the bundle.
The panel only knows each model as `M: Model`, so it can't call the `query`, `create`, `update`, and `delete` methods that `#[model]` gives each struct. It calls what those methods are made of instead, which Laravel exports but doesn't document. All four uses are in `src/model.rs`, so that a Laravel release that changes them changes one file.
## Working on the frontend
The frontend lives in `frontend/` and is built with [Bun](https://bun.sh), React, Tailwind CSS, and Vite into `crates/laravel-rust-admin/dist`, which is committed so that the crate builds without Node.
```shell
cd frontend
bun install
bun run dev # the Vite dev server, with hot reloading
bun run test # unit tests
bun run build # type-check, then write the bundle the crate embeds
```
To see your changes as you make them, run the demo against the dev server:
```shell
ADMIN_VITE_DEV_URL=http://localhost:5173 cargo run -p laravel-rust-admin-demo
```
The Rust side has its own tests, which run a real application against an in-memory database:
```shell
cargo test -p laravel-rust-admin --features sqlite
```
## Not there yet
- PostgreSQL and MySQL are untested. The queries go through Laravel's query builder, but nothing has run on those drivers.
- A form can't choose a related record. A foreign key is a plain number field for now.
- No file uploads.
- One panel per application.
- Selecting rows selects the rows on the current page, not every row that matches.
- A `Filter::select` compares its column as text.
- The panel is in English only.
## Credits
The panel takes after [Filament](https://filamentphp.com) in what it does and after [Flux](https://fluxui.dev) in how it looks. It shares no code with either, and isn't affiliated with them or with Laravel.
## License
MIT