Skip to content

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:

  1. 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.
  2. 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 ​

php
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]);
blade
{{ $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 sharing Column instances 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.
php
$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 ​

MethodWhenReceives
modifyQueryUsing(fn ($query, TableState $state, Table $table))before search, filters and sortingquery sources: the builder; memory sources: the Collection (a returned iterable replaces it)
afterResolve(fn (TableResult $result, Table $table))after the data is readythe result, for logging, preloading or auditing

Data without rendering ​

php
$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 included

Use TableResult for CSV exports, APIs and tests instead of parsing HTML.

Data sources ​

InputHandling
->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, generatorprocessed in memory
Paginator, CursorPaginatoralready paginated; rendered with pagination links
Closurereceives 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:

php
Table::make($columns)->records(
    fn (Table $table) => Order::search($table->getState()->search)->paginate(),
);

Columns ​

MethodPurpose
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 ​

php
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 ​

ClassPurpose
Columns\TextColumnview; same as Column
Columns\ViewColumnview; renders each cell with a Blade view: ->cellView('orders.cells.status')
Columns\ImageColumnpreview; thumbnails with circular(), size(), stackLimit(), preview(), urlUsing(). Only relative and http(s) URLs
Columns\TextInputColumnedit; text, number or date input
Columns\SelectColumnedit; select (array, enum or closure)
Columns\ToggleColumnedit; 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():

php
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.

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
KindAvailable
Operators+ - * / ^ %, & (concatenate), = <> != < > <= >=
LogicIF IFS AND OR NOT IFNULL COALESCE ISBLANK
MathROUND FLOOR CEILING ABS MOD POWER SQRT
AggregatesSUM AVG/AVERAGE COUNT COUNTA MIN MAX
TextCONCAT 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 ​

php
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; use page() or a memory source.
  • Summary values reuse the column's money() / numeric() formatting.

Relation aggregate columns ​

php
Column::make('orders_count')->counts('orders'),
Column::make('orders_sum_total')->sum('orders', 'total')->sortable(),
Column::make('reviews_avg_rating')->avg('reviews', 'rating'),

Grouping ​

php
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 ​

FilterActive whenDefault match
Filtercheckedwhere(field, true)
SelectFiltervalue is one of options() (array or enum), optionally multiple()where / whereIn
TernaryFilterall / yes / no; nullable() checks for nullwhere(field, bool) / whereNull
DateFiltera date or a from–to range, applied only when valid>= from, < day after to
DateTimeFiltersame, 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 ​

php
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 error

Accepted 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-31 and natural language such as next monday are 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 get min / max, and presets() 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 ​

php
$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 OFFSET

simple 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 ​

php
$table
    ->reorderableColumns()
    ->stickyHeader()
    ->stickyFooter()
    ->maxHeight('lg')     // sm / md / lg / xl / screen
    ->stackOn('md');      // label/value cards below the md container width

Column 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 ​

php
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 ​

php
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 ​

php
$table->reorderable('position', 'reorderRows', ['table' => 'tasks']);
php
#[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).

php
// 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));
php
// 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 ​

StateNo identifierqueryStringIdentifier('orders')
Searchsearchorders[search]
Sortsort, directionorders[sort], orders[direction]
Filtersfilters[status]orders[filters][status]
Per pageper_pageorders[per_page]
Visible columnscolumns[]orders[columns][]
Column orderorder[]orders[order][]
Groupgroup (- = none)orders[group]
Pagepage (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.
  • ImageColumn skips javascript: and data: URLs.

A full demo is available at /table-demo when CG_COMPONENT_SHOWCASE=true.