Data Display
data-table
Table built from columns and rows with client-side filter, sortable headers, row selection and pagination.
| Success | ken99@example.com | $316.00 | |
| Success | abe45@example.com | $242.00 | |
| Processing | monserrat44@example.com | $837.00 | |
| Success | silas22@example.com | $874.00 | |
| Failed | carmella@example.com | $721.00 | |
| Pending | lina.haddad@example.com | $45.00 | |
| Success | omar.k@example.com | $1,299.00 | |
| Processing | jules@example.com | $150.00 | |
| No results. | |||
0 of 8 row(s) selected.
@php
// In a real app these come from the controller.
$columns = [
'status' => 'Status',
'email' => 'Email',
'amount' => [
'label' => 'Amount',
'align' => 'end',
'format' => fn ($cents) => '$' . number_format($cents / 100, 2),
],
];
$payments = [
['id' => 'm5gr84i9', 'status' => 'Success', 'email' => 'ken99@example.com', 'amount' => 31600],
['id' => '3u1reuv4', 'status' => 'Success', 'email' => 'abe45@example.com', 'amount' => 24200],
['id' => 'derv1ws0', 'status' => 'Processing', 'email' => 'monserrat44@example.com', 'amount' => 83700],
['id' => '5kma53ae', 'status' => 'Success', 'email' => 'silas22@example.com', 'amount' => 87400],
['id' => 'bhqecj4p', 'status' => 'Failed', 'email' => 'carmella@example.com', 'amount' => 72100],
['id' => 'p0r8sd2k', 'status' => 'Pending', 'email' => 'lina.haddad@example.com', 'amount' => 4500],
['id' => 'x7c2lm9q', 'status' => 'Success', 'email' => 'omar.k@example.com', 'amount' => 129900],
['id' => 'h3n6tz1w', 'status' => 'Processing', 'email' => 'jules@example.com', 'amount' => 15000],
];
@endphp
<x-ui.data-table :columns="$columns" :rows="$payments" sortable selectable searchable :per-page="5"
class="w-full max-w-2xl" />
Installation
php artisan ui:add data-table
1. Install dependencies
- composer:
gehrisandro/tailwind-merge-laravel
2.
Copy the source into
resources/views/components/ui/
resources/views/components/ui/data-table.blade.php
@props([
'columns' => [],
'rows' => [],
'sortable' => false,
'selectable' => false,
'searchable' => false,
'perPage' => null,
'rowKey' => 'id',
'selectName' => 'selected',
'empty' => 'No results.',
'searchPlaceholder' => 'Filter...',
'searchLabel' => 'Filter rows',
'selectAllLabel' => 'Select all rows',
'selectRowLabel' => 'Select row',
'selectedLabel' => ':selected of :total row(s) selected.',
'previousLabel' => 'Previous',
'nextLabel' => 'Next',
'pageLabel' => 'Page :page of :pages',
])
@php
// Columns come as ['email' => 'Email'] or ['amount' => ['label' => 'Amount',
// 'align' => 'end', 'sortable' => true, 'format' => fn ($value, $row) => ...]].
// `format` changes what the cell shows; the raw value still drives sorting.
$cols = [];
foreach ($columns as $key => $column) {
$column = is_array($column) ? $column : ['label' => $column];
$cols[$key] = [
'label' => $column['label'] ?? $key,
'sortable' => $column['sortable'] ?? $sortable,
'format' => $column['format'] ?? null,
'align' => match ($column['align'] ?? 'start') {
'end' => 'text-end',
'center' => 'text-center',
default => 'text-start',
},
];
}
// Arrays, Collections and paginators all iterate the same way.
$items = iterator_to_array($rows, false);
$total = count($items);
$perPage = $perPage ? max(1, (int) $perPage) : null;
$pages = $perPage ? max(1, (int) ceil($total / $perPage)) : 1;
$classes = \TailwindMerge\Laravel\Facades\TailwindMerge::merge(
'group/data-table flex w-full flex-col gap-4',
$attributes->get('class'),
);
$checkbox = 'size-4 shrink-0 rounded-[4px] border border-input bg-transparent align-middle accent-primary shadow-xs outline-none transition-shadow disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]';
$pagerButton = 'inline-flex h-8 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-md border border-input bg-background px-3 text-sm font-medium text-foreground shadow-xs outline-none transition-all hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50 dark:bg-input/30 dark:hover:bg-input/50 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]';
@endphp
<div {{ $attributes->except('class')->merge(['class' => $classes]) }} data-ui-data-table
data-page="1" data-per-page="{{ $perPage }}" data-selected-label="{{ $selectedLabel }}"
data-page-label="{{ $pageLabel }}">
@if ($searchable)
<input type="search" data-ui-data-table-search placeholder="{{ $searchPlaceholder }}"
aria-label="{{ $searchLabel }}"
class="flex h-9 w-full min-w-0 max-w-sm rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none transition-[color,box-shadow] placeholder:text-muted-foreground md:text-sm dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]" />
@endif
<div class="relative w-full overflow-x-auto rounded-md border">
<table class="w-full caption-bottom text-sm">
<thead>
<tr>
@if ($selectable)
<th class="h-10 w-10 px-2 text-start">
<input type="checkbox" data-ui-data-table-select-all
aria-label="{{ $selectAllLabel }}" class="{{ $checkbox }}"
@disabled($total === 0) />
</th>
@endif
@foreach ($cols as $key => $col)
@if ($col['sortable'])
<th aria-sort="none"
class="group/sort h-10 px-2 font-medium text-muted-foreground {{ $col['align'] }}">
<button type="button" data-ui-data-table-sort="{{ $key }}"
class="-mx-2 inline-flex h-8 items-center gap-1.5 rounded-md px-2 outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-ring/50 focus-visible:ring-[3px]">
{{ $col['label'] }}
<svg class="size-3.5 group-aria-[sort=ascending]/sort:hidden group-aria-[sort=descending]/sort:hidden"
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round" aria-hidden="true">
<path d="m21 16-4 4-4-4" />
<path d="M17 20V4" />
<path d="m3 8 4-4 4 4" />
<path d="M7 4v16" />
</svg>
<svg class="hidden size-3.5 group-aria-[sort=ascending]/sort:block"
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round" aria-hidden="true">
<path d="m5 12 7-7 7 7" />
<path d="M12 19V5" />
</svg>
<svg class="hidden size-3.5 group-aria-[sort=descending]/sort:block"
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round" aria-hidden="true">
<path d="M12 5v14" />
<path d="m19 12-7 7-7-7" />
</svg>
</button>
</th>
@else
<th class="h-10 px-2 font-medium text-muted-foreground {{ $col['align'] }}">
{{ $col['label'] }}
</th>
@endif
@endforeach
</tr>
</thead>
<tbody data-ui-data-table-body>
@foreach ($items as $index => $row)
<tr data-ui-data-table-row data-index="{{ $index }}" @if ($perPage && $index >= $perPage) hidden @endif
class="border-t transition-colors hover:bg-muted/50 has-checked:bg-muted">
@if ($selectable)
<td class="w-10 p-2">
<input type="checkbox" data-ui-data-table-select name="{{ $selectName }}[]"
value="{{ data_get($row, $rowKey) }}" aria-label="{{ $selectRowLabel }}"
class="{{ $checkbox }}" />
</td>
@endif
@foreach ($cols as $key => $col)
@php
$value = data_get($row, $key);
$display = $col['format'] ? ($col['format'])($value, $row) : $value;
$sortValue = is_bool($value) ? (int) $value : (is_scalar($value) ? $value : $display);
@endphp
<td data-ui-data-table-cell="{{ $key }}" data-sort-value="{{ $sortValue }}"
class="p-2 {{ $col['align'] }}">{{ $display }}</td>
@endforeach
</tr>
@endforeach
</tbody>
<tbody data-ui-data-table-empty @if ($total > 0) hidden @endif>
<tr class="border-t">
<td colspan="{{ count($cols) + ($selectable ? 1 : 0) }}"
class="h-24 p-2 text-center text-muted-foreground">{{ $empty }}</td>
</tr>
</tbody>
</table>
</div>
@if ($selectable || $perPage)
<div class="flex flex-wrap items-center justify-between gap-4 text-sm text-muted-foreground">
<p data-ui-data-table-count aria-live="polite">
@if ($selectable)
{{ str_replace([':selected', ':total'], [0, $total], $selectedLabel) }}
@endif
</p>
@if ($perPage)
<div class="flex items-center gap-2">
<span data-ui-data-table-page aria-live="polite">{{ str_replace([':pages', ':page'], [$pages, 1], $pageLabel) }}</span>
<button type="button" data-ui-data-table-prev class="{{ $pagerButton }}" disabled>
{{ $previousLabel }}
</button>
<button type="button" data-ui-data-table-next class="{{ $pagerButton }}" @disabled($pages <= 1)>
{{ $nextLabel }}
</button>
</div>
@endif
</div>
@endif
</div>
@once
<script>
(function() {
if (window.__laralcnDataTable) return;
window.__laralcnDataTable = true;
function rows(root) {
return Array.prototype.slice.call(root.querySelectorAll('[data-ui-data-table-row]'));
}
// Rows the filter keeps. Pagination and select-all both work on these.
function matching(root) {
var search = root.querySelector('[data-ui-data-table-search]');
var query = search ? search.value.trim().toLowerCase() : '';
return rows(root).filter(function(row) {
return !query || row.textContent.toLowerCase().indexOf(query) !== -1;
});
}
function render(root) {
var all = rows(root);
var shown = matching(root);
var perPage = parseInt(root.dataset.perPage, 10) || 0;
var pages = perPage ? Math.max(1, Math.ceil(shown.length / perPage)) : 1;
var page = Math.min(Math.max(1, parseInt(root.dataset.page, 10) || 1), pages);
root.dataset.page = page;
all.forEach(function(row) { row.hidden = true; });
shown.forEach(function(row, i) {
row.hidden = perPage ? (i < (page - 1) * perPage || i >= page * perPage) : false;
});
root.querySelector('[data-ui-data-table-empty]').hidden = shown.length > 0;
var label = root.querySelector('[data-ui-data-table-page]');
if (label) {
label.textContent = root.dataset.pageLabel.replace(':pages', pages).replace(':page', page);
root.querySelector('[data-ui-data-table-prev]').disabled = page <= 1;
root.querySelector('[data-ui-data-table-next]').disabled = page >= pages;
}
syncSelection(root);
}
function syncSelection(root) {
var all = root.querySelectorAll('[data-ui-data-table-select]');
var head = root.querySelector('[data-ui-data-table-select-all]');
if (!head) return;
var boxes = matching(root).map(function(row) {
return row.querySelector('[data-ui-data-table-select]');
});
var on = boxes.filter(function(box) { return box.checked; }).length;
head.checked = boxes.length > 0 && on === boxes.length;
head.indeterminate = on > 0 && on < boxes.length;
head.disabled = boxes.length === 0;
var checked = Array.prototype.filter.call(all, function(box) { return box.checked; });
root.querySelector('[data-ui-data-table-count]').textContent = root.dataset.selectedLabel
.replace(':selected', checked.length).replace(':total', all.length);
return checked.map(function(box) { return box.value; });
}
function compare(a, b) {
if (a !== '' && b !== '' && isFinite(a) && isFinite(b)) return Number(a) - Number(b);
return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
}
function sort(button) {
var root = button.closest('[data-ui-data-table]');
var th = button.closest('th');
var next = { none: 'ascending', ascending: 'descending' }[th.getAttribute('aria-sort')] || 'none';
root.querySelectorAll('th[aria-sort]').forEach(function(other) {
other.setAttribute('aria-sort', 'none');
});
th.setAttribute('aria-sort', next);
var key = button.dataset.uiDataTableSort;
var value = function(row) {
var cell = row.querySelector('[data-ui-data-table-cell="' + CSS.escape(key) + '"]');
return cell ? cell.dataset.sortValue : '';
};
var body = root.querySelector('[data-ui-data-table-body]');
rows(root).sort(function(a, b) {
if (next === 'none') return a.dataset.index - b.dataset.index;
var result = compare(value(a), value(b));
return next === 'descending' ? -result : result;
}).forEach(function(row) { body.appendChild(row); });
render(root);
}
document.addEventListener('click', function(event) {
var button = event.target.closest('[data-ui-data-table-sort]');
if (button) return sort(button);
var pager = event.target.closest('[data-ui-data-table-prev], [data-ui-data-table-next]');
if (pager) {
var root = pager.closest('[data-ui-data-table]');
var step = pager.hasAttribute('data-ui-data-table-next') ? 1 : -1;
root.dataset.page = (parseInt(root.dataset.page, 10) || 1) + step;
render(root);
}
});
document.addEventListener('input', function(event) {
if (!event.target.matches('[data-ui-data-table-search]')) return;
var root = event.target.closest('[data-ui-data-table]');
root.dataset.page = 1;
render(root);
});
// The checkbox's own native change event bubbles to any listener first;
// this then keeps the header in sync and announces the full selection.
document.addEventListener('change', function(event) {
var box = event.target;
if (!box.matches('[data-ui-data-table-select], [data-ui-data-table-select-all]')) return;
var root = box.closest('[data-ui-data-table]');
if (box.matches('[data-ui-data-table-select-all]')) {
matching(root).forEach(function(row) {
row.querySelector('[data-ui-data-table-select]').checked = box.checked;
});
}
root.dispatchEvent(new CustomEvent('data-table-select', {
bubbles: true,
detail: { selected: syncSelection(root) },
}));
});
})();
</script>
@endonce
Usage
{{-- Plain columns, nothing interactive --}}
<x-ui.data-table :columns="['email' => 'Email', 'amount' => 'Amount']" :rows="$payments" />
{{-- Every feature on. `format` changes what a cell shows; the raw value still sorts. --}}
<x-ui.data-table
:columns="[
'email' => 'Email',
'amount' => ['label' => 'Amount', 'align' => 'end', 'format' => fn ($cents) => '$' . number_format($cents / 100, 2)],
]"
:rows="$payments" sortable selectable searchable :per-page="10" />
{{-- Inside a form the checked rows submit as ids[] --}}
<form method="POST" action="/payments/bulk-refund">
@csrf
<x-ui.data-table :columns="$columns" :rows="$payments" selectable select-name="ids" row-key="id" />
<x-ui.button type="submit">Refund selected</x-ui.button>
</form>
{{-- Large data: paginate on the server and render the pagination component below --}}
<x-ui.data-table :columns="$columns" :rows="$payments->items()" sortable />
<script>
document.addEventListener('data-table-select', (event) => {
console.log(event.detail.selected); // ['m5gr84i9', ...]
});
</script>
Pass columns (['email' => 'Email'] or ['amount' => ['label' => 'Amount', 'align' => 'end', 'format' => fn ($value, $row) => ...]]) and rows (arrays or objects); format changes the display while the raw value drives sorting. sortable, searchable, selectable and per-page work on the rendered rows only, so pass a paginator's items and render pagination below for large data. Selected rows submit as selected[] (select-name, value from row-key), and the root fires data-table-select with detail.selected.
Props
Every prop with its default. Pass any of them as attributes, using : to bind a PHP value.
@props([
'columns' => [],
'rows' => [],
'sortable' => false,
'selectable' => false,
'searchable' => false,
'perPage' => null,
'rowKey' => 'id',
'selectName' => 'selected',
'empty' => 'No results.',
'searchPlaceholder' => 'Filter...',
'searchLabel' => 'Filter rows',
'selectAllLabel' => 'Select all rows',
'selectRowLabel' => 'Select row',
'selectedLabel' => ':selected of :total row(s) selected.',
'previousLabel' => 'Previous',
'nextLabel' => 'Next',
'pageLabel' => 'Page :page of :pages',
])