Tables
Table is a data table inspired by Filament Tables: you declare columns, filters and groups; the table reads state, queries data, computes summaries and renders HTML. Two things are different from Filament:
- No restricted bootstrapping environment. A table is a plain PHP object. Create and render it in a controller, a Blade view, a renderBlade fragment, a job or a test — as many times as you like, and as many tables per page as you like, without them affecting each other.
- No Livewire. Search, filters, sorting, pagination, grouping, column visibility and column order all live in the GET query string. Every state is bookmarkable and shareable, and everything works without JavaScript. JavaScript only makes expanding, copying and dragging smoother.
Quick start
use App\Component\Table\Column;
use App\Component\Table\Filters\SelectFilter;
use App\Component\Table\Summaries\Sum;
use App\Component\Table\Table;
$table = Table::make([
Column::make('number', 'Number')->searchable()->sortable()->copyable(),
Column::make('customer.name', 'Customer')->searchable()->sortable(), // Eloquent relation
Column::make('status', 'Status')->badge(['paid' => 'success', 'pending' => 'warning']),
Column::make('total', 'Total')->money('USD')->align('end')->sortable()
->summarize(Sum::make()),
])
->query(Order::query())
->filters([
SelectFilter::make('status', 'Status')->options(OrderStatus::class)->multiple(),
])
->defaultSort('created_at', 'desc')
->paginate(25, [10, 25, 50]);{{ $table }}Lifecycle and multiple tables
A table has no global state and is not tied to a Page or Schema:
- Every
resolve()/toHtml()creates a fresh data source (builders are cloned first) and a fresh column index. Rendering the same table twice gives the same result, and sharingColumninstances between tables is safe. - Use
queryStringIdentifier()to namespace each table's parameters (orders[search],orders_page). Links and forms generated by one table preserve the other tables' parameters. copy()returns a deep copy; changing the copy never touches the original.
$base = Table::make($columns)->query(Order::query());
$paid = $base->copy()->queryStringIdentifier('paid')->modifyQueryUsing(fn ($q) => $q->where('status', 'paid'));
$pending = $base->copy()->queryStringIdentifier('pending')->modifyQueryUsing(fn ($q) => $q->where('status', 'pending'));Lifecycle hooks
| Method | When | Receives |
|---|---|---|
modifyQueryUsing(fn ($query, TableState $state, Table $table)) | before search, filters and sorting | query sources: the builder; memory sources: the Collection (a returned iterable replaces it) |
afterResolve(fn (TableResult $result, Table $table)) | after the data is ready | the result, for logging, preloading or auditing |
Data without rendering
$result = $table->resolve();
$result->records(); // records on this page
$result->paginator; // Paginator / CursorPaginator / null
$result->summaries['all']['total']; // summary values (raw value and formatted html)
$result->state($result->rows[0], 'subtotal'); // raw value of a cell, formulas includedUse TableResult for CSV exports, APIs and tests instead of parsing HTML.
Data sources
| Input | Handling |
|---|---|
->model(Order::class), ->query(Order::query()), a relation ($user->orders()) | search, filters, sorting, pagination and summaries in the database |
->records(DB::table('orders')) | same; dotted keys mean table.column |
array, Collection, LazyCollection, generator | processed in memory |
Paginator, CursorPaginator | already paginated; rendered with pagination links |
| Closure | receives the table and returns any of the above |
Dotted Eloquent keys (customer.name) are detected as relations: search and filters use whereHas, sorting uses a withAggregate subquery (no join, pagination counts unaffected), and the relation is eager loaded to avoid N+1 queries (eagerLoadRelations(false) turns it off).
A pre-paginated paginator cannot be searched correctly. To run your own query with the table's state:
Table::make($columns)->records(
fn (Table $table) => Order::search($table->getState()->search)->paginate(),
);Columns
| Method | Purpose |
|---|---|
searchable() / searchable(['name', 'email']) / searchUsing(fn ($q, $s)) | global search |
sortable() / sortAttribute() / sortUsing(fn ($q, $dir)) | table-managed sorting (passing a URL or linkerSort() keeps external sorting) |
toggleable(hiddenByDefault: false) | listed in the Columns menu |
collapsible() | moved into the expandable row panel |
copyable() | copy button (shown once JavaScript is active) |
colspan(int|fn ($record)) | span the next columns in this row |
visibleFrom('md') | hidden when the container is narrower than the breakpoint |
date() dateTime() numeric() money() limit() prefix() suffix() | formatting |
badge() boolean() description() placeholder() | presentation |
formatStateUsing() / stateUsing() | full control (wins over built-in formatting) |
Column groups
use App\Component\Table\ColumnGroup;
Table::make([
Column::make('number', 'Number'),
ColumnGroup::make('Amount', [
Column::make('price', 'Price'),
Column::make('qty', 'Qty'),
Column::make('subtotal', 'Subtotal')->formula('=price * qty'),
])->key('amount'),
]);Two header rows are rendered: the group heading with scope="colgroup", other columns with rowspan="2". Toggling columns inside the group adjusts its colspan; a group whose columns are all hidden disappears.
Column subclasses: view, preview, edit
| Class | Purpose |
|---|---|
Columns\TextColumn | view; same as Column |
Columns\ViewColumn | view; renders each cell with a Blade view: ->cellView('orders.cells.status') |
Columns\ImageColumn | preview; thumbnails with circular(), size(), stackLimit(), preview(), urlUsing(). Only relative and http(s) URLs |
Columns\TextInputColumn | edit; text, number or date input |
Columns\SelectColumn | edit; select (array, enum or closure) |
Columns\ToggleColumn | edit; switch |
Editable columns submit either through a Linker method (linkerUpdate('updateCell'), arguments {row, column, value, ...extra}) or as form fields named "{column}[{rowKey}]" inside a surrounding Form.
To build your own column, override formatCellState():
class ProgressColumn extends Column
{
protected function formatCellState(mixed $state, mixed $record, int|string $rowKey, int $rowIndex): mixed
{
$percent = max(0, min(100, (int) $state));
return new HtmlString('<progress max="100" value="'.$percent.'">'.$percent.'%</progress>');
}
}Excel-like formulas
Formula columns compute values from other columns in the same row (or any attribute of the record). Formulas are parsed into an AST and evaluated with a whitelist of functions — no eval, no arbitrary PHP.
Column::make('subtotal')->formula('=price * qty')->numeric(),
Column::make('taxed')->formula('=ROUND(subtotal * 1.05, 0)'), // formulas can reference formulas
Column::make('final')->formula('=IF(qty >= 10, subtotal * 0.9, subtotal)'),
Column::make('label')->formula('="#" & number & " (" & UPPER(status) & ")"'),
Column::make('rate')->formula('=[customer.discount] * 100 & "%"'), // [brackets] wrap any key| Kind | Available |
|---|---|
| Operators | + - * / ^ %, & (concatenate), = <> != < > <= >= |
| Logic | IF IFS AND OR NOT IFNULL COALESCE ISBLANK |
| Math | ROUND FLOOR CEILING ABS MOD POWER SQRT |
| Aggregates | SUM AVG/AVERAGE COUNT COUNTA MIN MAX |
| Text | CONCAT UPPER LOWER LEN TRIM LEFT RIGHT |
Errors show up in the cell as Excel error values: #DIV/0!, #VALUE!, #NAME?, #CYCLE!. Syntax errors throw when the column is declared. IF short-circuits.
Formula columns can be searched and sorted with memory sources; databases cannot evaluate them, so use sortUsing() / searchable([...]) there.
Summaries
use App\Component\Table\Summaries\{Average, Count, Formula, Max, Min, Sum};
Column::make('total')->money('USD')->summarize([
Sum::make(), // all matching records
Sum::make('Page')->page(), // current page only
Average::make(),
]),
Column::make('number')->summarize(Count::make()),
Column::make('subtotal')->formula('=price * qty')->summarize([
Sum::make()->page(),
Formula::using('=ROUND(SUM(subtotal) * 1.05, 0)', 'With tax'),
]),- Summaries render in
<tfoot>(page subtotal and grand total rows) and as a subtotal row per group. all()(the default) runs one aggregate query for database sources without loading records.- Formula,
stateUsing()and relation columns cannot be aggregated in the database; usepage()or a memory source. - Summary values reuse the column's
money()/numeric()formatting.
Relation aggregate columns
Column::make('orders_count')->counts('orders'),
Column::make('orders_sum_total')->sum('orders', 'total')->sortable(),
Column::make('reviews_avg_rating')->avg('reviews', 'rating'),Grouping
use App\Component\Table\Grouping\Group;
$table->groupBy(Group::make('status', 'Status')->collapsible());
$table->groups([
Group::make('status', 'Status'),
Group::make('customer.name', 'Customer'),
Group::make('created_at', 'Date')->keyUsing(fn ($order) => $order->created_at->toDateString()),
])->defaultGroup('status');Records are ordered by the group first, then by the user's sort. Each group gets a heading row (with a count) and a subtotal row. Users can only pick declared groups.
Filters, search and sorting
| Filter | Active when | Default match |
|---|---|---|
Filter | checked | where(field, true) |
SelectFilter | value is one of options() (array or enum), optionally multiple() | where / whereIn |
TernaryFilter | all / yes / no; nullable() checks for null | where(field, bool) / whereNull |
DateFilter | a date or a from–to range, applied only when valid | >= from, < day after to |
DateTimeFilter | same, to the minute (withSeconds() for seconds) | >= from, < minute after to |
field('customer.tier') works for both database and memory sources. Customize with query(fn ($query, $value)) and filterRecordsUsing(fn ($record, $value): bool). Defaults apply until the filter form is submitted. Sorting cycles ascending → descending → default.
Date filters
use App\Component\Table\Filters\DateFilter;
use App\Component\Table\Filters\DateTimeFilter;
DateFilter::make('created_at', 'Created')
->range('2026-11-12', '2026-12-12') // selectable window
->presets(['-7d' => 'Last 7 days', '-1M' => 'Last month']) // relative period shortcuts
->default('-7d');
DateTimeFilter::make('paid_at', 'Paid at')
->range('-30d') // past 30 days until now, recomputed on every render
->multiple(3) // up to three ranges, any of them matches
->validateOrder(false); // swap from/to instead of reporting an errorAccepted values (for default(), range() and the query string): Carbon / DateTimeInterface, CarbonPeriod, date strings (2026-11-12, 2026/11/12, 2026-11-12 08:30), range strings (2026-11-12~2026-12-12, either end may be empty), relative periods (-7d, +5h, 1M2w), arrays (['from' => …, 'to' => …], ['period' => '-7d']), and lists of any of these for multiple ranges.
Relative period syntax: [+|-]amount unit, chainable (1M2w). - means past until now (no sign is the same as -); + means now until the future. Units: s second, m minute, H hour, D day, W week, M month, S quarter, Y year. s/S and m/M are case sensitive; hour, day, week and year are not. Full-width characters are converted.
Validation: if any rule fails the filter is not applied, the message is shown under the control, the input is refilled as typed, and the filter dropdown opens.
- Dates must exist:
2026-02-31and natural language such asnext mondayare rejected. - From must not be later than to (the same day is fine).
validateOrder(false)swaps the ends instead. - Values must fall inside
range(). With several windows a range must fit inside one of them. An open end is clamped to the window, so nothing outside the window is queried. Inputs also getmin/max, andpresets()that fall outside the range today are disabled. - No more ranges than
multiple()allows (one by default).
Matching: the end is converted to the exclusive next unit, so "to 12/12" includes all of 12/12. DateFilter compares the date part only (2026-11-12 strings work on both date and datetime columns and use indexes). DateTimeFilter compares full timestamps; a date-only end covers the whole day. Values are read in config('app.timezone').
between(false) switches to a single date; fromLabel() / toLabel() change the accessible labels.
Pagination
$table->paginate(25, [10, 25, 50]);
$table->perPageOptions([20, 50, 100]);
$table->paginationMode('length'); // default: LIMIT/OFFSET with COUNT
$table->simplePagination(); // LIMIT/OFFSET without COUNT
$table->cursorPagination(); // cursor: no COUNT, no OFFSETsimple and cursor never run a COUNT query. Cursor pagination appends the primary key as a tie-breaker; it cannot be combined with relation sorting or row reordering.
Column toggling, order and responsiveness
$table
->reorderableColumns()
->stickyHeader()
->stickyFooter()
->maxHeight('lg') // sm / md / lg / xl / screen
->stackOn('md'); // label/value cards below the md container widthColumn visibility (columns[]) and order (order[]) are stored in the URL. With JavaScript they update instantly; layouts with spanning cells (ColumnGroup, colspan, transposed) navigate to the new URL instead. Responsiveness uses container queries, so a table in a narrow sidebar stacks correctly.
Transposed tables
Table::make($columns)->records($plans)->transpose()->recordTitle('name');Columns become rows (th scope="row") and records become columns. Summaries appear as extra columns. Not available together with groups(), detail() or reorderable().
Expandable rows
Column::make('note')->collapsible(),
$table->detail(fn (Order $order) => view('orders.timeline', compact('order')));Without JavaScript the toggle is a real #anchor expanded with CSS :target; with JavaScript several rows can be open at once.
Reordering rows
$table->reorderable('position', 'reorderRows', ['table' => 'tasks']);#[Computable]
#[Validate(['order' => 'required|array|max:500', 'order.*' => 'integer', 'offset' => 'integer|min:0'])]
public function reorderRows(array $args): LinkerResponse
{
Table::persistOrder(Task::where('project_id', $this->projectId), $args['order'], 'position', (int) ($args['offset'] ?? 0));
return $this->ok([]);
}persistOrder() only updates records inside the given query that appear in the list. Dragging pauses while another sort or a group is active. Keyboard users focus the handle and press ↑/↓.
Loading and driving a table with Linker
By default every interaction is a full-page GET. Put the table inside a Linker mount point with @renderAuto and the page ships a skeleton, loads the table afterwards, and re-renders only the table on sort, filter, page and column changes. /table-demo ends with complete Stateless and Stateful examples (sign-in required).
// Fragment controller: rebuild the table from the untrusted query string
parse_str((string) ($params['query'] ?? ''), $input);
$table = $this->ordersTable()
->linkerNavigation('navigate') // links and toolbar forms call navigate() on the enclosing mount
->request(Request::create(route('orders.index'), 'GET', $input));// Linker: answer with render.fragment
#[Computable]
#[Validate(['query' => 'nullable|string|max:2000'])]
public function navigate(array $args): LinkerResponse
{
return $this->ok()->call('render.fragment', [
'target' => '#orders-table',
'name' => OrderController::class,
'params' => ['query' => (string) ($args['query'] ?? '')],
]);
}A Stateless linker re-renders whatever state each call carries. A Stateful linker keeps the state in its instance, so it can re-render without arguments and keep a history for "back". Reloading the page starts over in both modes. Links keep real hrefs (new tabs and no-JS still work), the current state lives in the table's data-table-url rather than the address bar, and pagination links use the URL given to request().
Query string reference
| State | No identifier | queryStringIdentifier('orders') |
|---|---|---|
| Search | search | orders[search] |
| Sort | sort, direction | orders[sort], orders[direction] |
| Filters | filters[status] | orders[filters][status] |
| Per page | per_page | orders[per_page] |
| Visible columns | columns[] | orders[columns][] |
| Column order | order[] | orders[order][] |
| Group | group (- = none) | orders[group] |
| Page | page (cursor: cursor) | orders_page (orders_cursor) |
Security
- Only declared sortable columns, declared groups, declared select options and declared per-page values are accepted; anything else is ignored.
- Search terms are truncated to 200 characters and always bound as parameters.
- Cell content is escaped unless it is
Htmlable. - Formulas can only call whitelisted functions.
ImageColumnskipsjavascript:anddata:URLs.
A full demo is available at /table-demo when CG_COMPONENT_SHOWCASE=true.