Table

Rows of records. Covers table, table-row and table-cell.

Table

A tree table needs Alpine and the package's script (tree, below). See getting started. With JavaScript off it shows every row and no toggles. A plain table needs neither.

Use it

Headers come from the columns prop, not from a slot:

<x-ds::table :columns="['Report', 'Status', ['label' => 'Total', 'align' => 'right']]">
    @foreach ($reports as $report)
        <x-ds::table-row>
            <x-ds::table-cell>
                <a href="{{ route('reports.show', $report) }}" class="font-medium text-fg hover:underline">{{ $report->name }}</a>
            </x-ds::table-cell>
            <x-ds::table-cell :nowrap="true">
                <x-ds::badge :tone="$report->tone">{{ $report->status }}</x-ds::badge>
            </x-ds::table-cell>
            <x-ds::table-cell align="right">{{ $report->total }}</x-ds::table-cell>
        </x-ds::table-row>
    @endforeach
</x-ds::table>

columns

Each entry is either a label, or an array:

['label' => 'Joined', 'align' => 'right', 'width' => 'w-36']
KeyValuesWhat it does
labelstringThe header text. An empty string reserves the column without a heading — for an actions column.
alignleft center rightDefaults to left.
widthTailwind classFixes the column width.
sortableboolThe reader can sort by this column: its header becomes a link or button. See Sorting.
keystringThe name the server sorts this column by. Required with sortable; the entry's own array key works too.

Omit columns entirely and supply your own <thead> in the slot.

width is a class from your source. It works because Tailwind scans your views and finds the literal w-36 there. Build it dynamically — 'w-'.$n — and it silently has no rule and no width. Write it out.

Sorting

The table says which column the rows are sorted by and lets the reader ask for another order. It never sorts anything itself: your query does, from the sort and direction it is given.

<x-ds::table
    :sort="request('sort', 'created_at')"
    :direction="request('direction', 'desc')"
    :columns="[
        ['label' => 'Report', 'key' => 'name', 'sortable' => true],
        'Status',
        ['label' => 'Total', 'key' => 'total', 'align' => 'right', 'sortable' => true],
        ['label' => 'Created', 'key' => 'created_at', 'sortable' => true],
    ]"
>
    @foreach ($reports as $report) … @endforeach
</x-ds::table>
$reports = Report::query()
    ->orderBy(in_array($request->sort, ['name', 'total', 'created_at']) ? $request->sort : 'created_at',
              $request->direction === 'asc' ? 'asc' : 'desc')
    ->paginate();

Each sortable header is a link. A press on the sorted column asks for the other direction; a press on any other asks for ascending. By default the link is the current URL with sort and direction set in the query string and page dropped, since a new order starts on page one. Validate both against a list of your own before they reach a query, as above.

Sortable table

PropTypeDefaultWhat it does
sortstring—The key of the column the rows are sorted by.
directionstringascasc or desc.
sortUrlstring, Closure—Where a header links instead of the default: a pattern such as /reports?order={key}&dir={direction}, or fn ($key, $direction) => route('reports.index', [...]). {direction} is the one the press asks for. Without either, the current URL with sort and direction (and no page); inside a Livewire update that is the page's URL, not Livewire's endpoint.
sortActionstring, Closure—For Livewire: the header becomes a button with this wire:click, a pattern such as sortBy('{key}') or a closure. Wins over sortUrl.

With Livewire

<x-ds::table :sort="$sort" :direction="$direction" sortAction="sortBy('{key}')" :columns="$columns">
public string $sort = 'created_at';
public string $direction = 'desc';

public function sortBy(string $key): void
{
    $this->direction = $this->sort === $key && $this->direction === 'asc' ? 'desc' : 'asc';
    $this->sort = $key;
    $this->resetPage();
}

A plain link would reload the page, which is why Livewire gets a button. The default link reads the current request's URL, which inside a Livewire update is Livewire's own endpoint: pass sortAction, not nothing.

What the reader sees

  • The sorted column's label is full strength, with an arrow: up for ascending, down for descending.
  • Every other sortable header shows a faint up-and-down arrow under the pointer or keyboard focus, in space that is always kept, so the label never moves.
  • On a right-aligned column the arrow sits inside the label, so the label's edge stays on the figures' edge.

table-row and table-cell

ComponentPropDefaultWhat it does
table-rowhovertrueRow hover fill.
table-rowlevel—In a tree table: how deep the row is, from 1.
table-rowexpandablefalseIn a tree table: the row has rows under it, closed.
table-rowopenfalseIn a tree table: the row has rows under it, open. Implies expandable.
table-rowparent—In a tree table: the parent row's id, checked against the order.
table-cellalignleftleft center right.
table-cellnowrapfalseStops the cell wrapping.
table-cellrowHeaderfalseThe cell names its row: a <th scope="row"> in the heading colour. Usually the first.

A class on a cell joins the cell's own (before 2.0 it was dropped).

nowrap is right for dates, counts and badges; wrong for prose — a non-wrapping sentence forces the whole table sideways.

Tree table

Rows that nest: accounts and sub-accounts, a budget's lines, a folder's files with their sizes. Pass tree to the table and a level to every row, in display order, each child straight after its parent:

<x-ds::table tree label="Accounts" :columns="['Account', 'Owner', ['label' => 'Balance', 'align' => 'right']]">
    @foreach ($accounts as $account)   {{-- depth-first: each parent, then its children --}}
        <x-ds::table-row
            :id="'account-'.$account->id"
            :level="$account->depth"
            :expandable="$account->has_children"
            :open="in_array($account->id, $open)"
        >
            <x-ds::table-cell><a href="{{ route('accounts.show', $account) }}">{{ $account->name }}</a></x-ds::table-cell>
            <x-ds::table-cell>{{ $account->owner }}</x-ds::table-cell>
            <x-ds::table-cell align="right">{{ $account->balance }}</x-ds::table-cell>
        </x-ds::table-row>
    @endforeach
</x-ds::table>
PropTypeDefaultWhat it does
treeboolfalseMakes the table a treegrid.
labelstring—The table's name, a visually hidden caption. Works on any table.
  • The rows are flat and the structure is level and order. The server counts each row's place among its siblings and hides every row under a closed one, so the first paint is right.
  • The first cell gets the indent and a chevron button; a row with no rows under it gets a spacer, so the names line up.
  • A row whose next row is deeper must be expandable or open; a level that jumps by two, or a parent that does not match the order, throws while you build the page.
  • Closing a row hides everything under it and remembers what was open inside, so opening it again brings it back as it was.

Keys, after the WAI-ARIA treegrid pattern with rows focused: the rows are one Tab stop; Up and Down move between the rows showing; Right opens a row, then moves to its first child; Left closes it, then moves to its parent; Home and End; typing jumps to a row by its first cell. Enter follows the row's first link, or opens and closes a row without one. Links and buttons in the cells are Tab stops of their own.

Sorting is yours. Sort the siblings in your query and keep each child after its parent; a sortable column on a tree table sorts nothing by itself.

Without the script every row shows. With JavaScript off, and with Alpine but no <x-ds::scripts />, nothing could open a closed row again, so the rows under closed rows show and the chevrons are hidden (their space kept). Only where the script runs are closed rows hidden.

Loading children, with Livewire

Opening or closing a row dispatches expand or collapse, bubbling, with detail.id, the row's id. Keep the open rows on the component, load the children when one opens, and give every row a wire:key so a morph matches them:

<div x-on:expand="$wire.open($event.detail.id)" x-on:collapse="$wire.close($event.detail.id)">
    <x-ds::table tree label="Accounts">
        @foreach ($this->rows as $row)
            <x-ds::table-row wire:key="row-{{ $row->id }}" :id="'row-'.$row->id" :level="$row->depth"
                :expandable="$row->has_children" :open="in_array('row-'.$row->id, $opened)">
                …
            </x-ds::table-row>
        @endforeach
    </x-ds::table>
</div>

Without that, a re-render puts every row back as the server last drew it.

A row's header

Give the cell that names the row rowHeader, and a screen reader moving down a column says which row it is in: "Acme Corp, Plan, Team".

<x-ds::table-row>
    <x-ds::table-cell :rowHeader="true">{{ $customer->name }}</x-ds::table-cell>
    <x-ds::table-cell>{{ $customer->plan }}</x-ds::table-cell>
</x-ds::table-row>

Your own head, and groups of rows

columns draws a head of plain labels. For anything else (a header row whose cells hide on a phone, two header rows) write the rows in a head slot; the table gives them the thead:

<x-ds::table label="Permissions by role">
    <x-slot:head>
        <tr>
            <th scope="col" class="px-4 py-3 text-left text-overline uppercase text-fg-muted">Permission</th>
            …
        </tr>
    </x-slot:head>

    @foreach ($areas as $area => $permissions)
        <tbody>
            <tr><th scope="rowgroup" colspan="4" …>{{ $area }}</th></tr>
            …
        </tbody>
    @endforeach
</x-ds::table>

A slot that starts with its own <tbody> is the table's body as written, one tbody per group; anything else is rows, and goes in the table's.

Sticky head and first column

<x-ds::table :columns="$columns" :stickyHead="true" :stickyFirst="true" class="max-h-96">
  • stickyHead keeps the header row at the top while the rows scroll under it. The table scrolls in its own box, so give it a height (class="max-h-96"); without one it is as tall as its rows and nothing moves.
  • stickyFirst keeps the first column while the others scroll sideways, and with selectable the boxes and the column after them. Make that column a rowHeader, and keep it narrow on a phone.

A shadow shows under the head, or beside the column, once something has scrolled under it, and not before. It needs a browser with scroll-driven animations; elsewhere the cells still stick, with no shadow.

A cell's own background class still wins over the sticky one, so a group's header row can keep its fill.

Loading

loading draws the head and loadingRows (5) rows of skeletons, sets aria-busy, says loadingLabel ("Loading") to a screen reader, and leaves the slot out. The table keeps its place and its columns, so nothing jumps when the rows arrive:

<x-ds::table :columns="$columns" :loading="$report === null">
    @foreach ($report?->rows ?? [] as $row) … @endforeach
</x-ds::table>

With Livewire, return it from a lazy component's placeholder(). Skeleton swap cannot hold rows (a table's body takes only rows), which is why the table has its own.

Selecting rows

selectable puts a checkbox on every row given a value, posting selected[], and with columns a select-all box in the header. With the package's script the select-all box goes mixed and full, and Shift with a press, or Shift+Space on a focused box, selects a run:

<x-ds::table id="invoices" selectable :columns="['Invoice', 'Total']">
    @foreach ($invoices as $invoice)
        <x-ds::table-row :value="$invoice->id" :selectLabel="'Select invoice '.$invoice->number">
            <x-ds::table-cell>{{ $invoice->number }}</x-ds::table-cell>
            <x-ds::table-cell>{{ $invoice->total }}</x-ds::table-cell>
        </x-ds::table-row>
    @endforeach
</x-ds::table>

The bulk actions belong in a selection bar, which has the full table of props (selectName, selectModel, selectAllLabel, and the row's value, selected, selectLabel). Not with tree.

Linking a row

table-row has no href. A <tr> cannot be a link, and wrapping one in an <a> is invalid HTML. Until v1.2.1 this page documented an href prop that the component never had: it rendered <tr href="…">, which the browser ignores, and the row looked clickable and went nowhere.

Link from a cell instead, either the first cell's text or a trailing action:

<x-ds::table-row>
    <x-ds::table-cell>{{ $report->name }}</x-ds::table-cell>
    <x-ds::table-cell align="right">
        <x-ds::button variant="ghost" size="sm" :href="route('reports.show', $report)">View</x-ds::button>
    </x-ds::table-cell>
</x-ds::table-row>

Both are real links: they take focus, open in a new tab, and carry anything else you put on them, such as Livewire's wire:navigate.

It scrolls inside its own box

The table sits in an overflow-x-auto container, so a wide table scrolls within its rounded border rather than pushing the page sideways. On a phone, a page that scrolls horizontally is indistinguishable from a broken one.

Empty tables

Keep the header and put an empty state in the body — the reader needs to know what is empty:

<x-ds::table :columns="['Report', 'Status']">
    @forelse ($reports as $report)
        …
    @empty
        <tr><td colspan="2">
            <x-ds::empty-state title="No reports yet" :bare="true" />
        </td></tr>
    @endforelse
</x-ds::table>

Accessibility

  • Headers are th scope="col"; a rowHeader cell is th scope="row".
  • The sorted column's header carries aria-sort="ascending" or "descending"; no other header has aria-sort, so a screen reader names one sort and only one.
  • Each sortable header is a real link or button inside the th, named by its label, reachable by Tab and pressed with Enter. The arrow is decorative (aria-hidden): the state is in aria-sort.
  • A tree table is a treegrid: each row has aria-level, aria-setsize, aria-posinset, and aria-expanded when it has rows under it. Its toggle is a button named "Expand Acme Corp" or "Collapse Acme Corp", out of the Tab order: the row is the stop.
  • A loading table is aria-busy, its skeleton rows hidden, and a hidden cell says loadingLabel.

Don't

  • Don't sort in the view. The table presents an order; the query makes it.
  • Don't pass sort and direction from the request into a query unchecked. Compare them against your own list of columns.
  • Don't make the row itself the link. See above: link a cell.
  • Don't build width dynamically. See above.
  • Don't use a table for layout.
  • Don't nest a tree table deeper than a reader can follow. Past three or four levels, link to the deeper record instead.

More in specs/table.md.


From the package repo: edit this page on GitHub.

Was this page helpful?