---
title: "Laravel Inertia Datatable: Build It Yourself"
description: "Build a Laravel Inertia datatable with server-side search, sorting, filters and pagination, state in the URL, Vue and React code, and accessible headers."
pageClass: blog-page
date: 2026-10-24
author: erag
category: frontend
tags: [Inertia, Tables]
---
# Laravel Inertia Datatable: Server-Side Search, Sort, Filters and Pagination
Search for a Laravel Inertia datatable and you'll mostly find packages. Some are good, but a users or invoices table is something you'll build a dozen times in a SaaS app, and once you know the pattern it's not much code. You also keep full control over the queries, the markup and the design system.
This guide builds one table from end to end. On the server: a validated request, a whitelist of sortable columns, a service that builds the query, and `paginate()->withQueryString()`. On the client: debounced search, sortable headers, filters, pagination links, a loading state, and all of it kept in the URL so a refresh or a shared link shows the same view.
We're using Laravel 13, PHP 8.4 and Inertia v3 (`inertiajs/inertia-laravel` 3.5, `@inertiajs/vue3` 3.9). Vue is the main example, with a shorter React version after it.
## How the table works
Everything the table shows is decided by the query string:
```text
/users?search=ann&role=admin&sort=name&direction=asc&per_page=25&page=2
```
The browser changes the query string with `router.get()`. Laravel validates it, runs one query, and returns the current page plus the active filters. Nothing is filtered in JavaScript. That's what makes it work for 50 rows or 5 million.
## Validate the table parameters
Start with a Form Request. Its job is to make sure nothing unexpected reaches the query, especially the sort column:
```php
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UserIndexRequest extends FormRequest
{
public const array SORTABLE = ['name', 'email', 'created_at'];
public const array PER_PAGE = [10, 25, 50];
public function rules(): array
{
return [
'search' => ['nullable', 'string', 'max:100'],
'status' => ['nullable', Rule::in(['verified', 'unverified'])],
'role' => ['nullable', 'string', 'exists:roles,name'],
'sort' => ['nullable', Rule::in(self::SORTABLE)],
'direction' => ['nullable', Rule::in(['asc', 'desc'])],
'per_page' => ['nullable', 'integer', Rule::in(self::PER_PAGE)],
];
}
public function tableQuery(): UserTableQuery
{
return new UserTableQuery(
search: $this->validated('search'),
status: $this->validated('status'),
role: $this->validated('role'),
sort: $this->validated('sort') ?? 'created_at',
direction: $this->validated('direction') ?? 'desc',
perPage: (int) ($this->validated('per_page') ?? 10),
);
}
}
```
The sort whitelist is the important line. `orderBy()` checks the direction for you, but the column name goes into the SQL as it is. If you pass `$request->sort` straight to `orderBy()`, users can sort by any column, including ones you never meant to expose. `Rule::in()` closes that.
Laravel's default middleware already trims strings and turns empty ones into `null`, so `?search=` arrives as `null`.
`UserTableQuery` is a small readonly object, so the service gets typed values instead of a loose array:
```php
final readonly class UserTableQuery
{
public function __construct(
public ?string $search,
public ?string $status,
public ?string $role,
public string $sort,
public string $direction,
public int $perPage,
) {}
/** @return array */
public function toArray(): array
{
return [
'search' => $this->search,
'status' => $this->status,
'role' => $this->role,
'sort' => $this->sort,
'direction' => $this->direction,
'per_page' => $this->perPage,
];
}
}
```
## Build the query in a service
The query lives in a service, not the controller:
```php
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
class UserTableService
{
public function paginate(UserTableQuery $query): LengthAwarePaginator
{
return User::query()
->select(['id', 'name', 'email', 'email_verified_at', 'created_at'])
->with('roles:id,name')
->when($query->search, function (Builder $builder, string $search): void {
$builder->where(function (Builder $builder) use ($search): void {
$builder->whereLike('name', "%{$search}%")
->orWhereLike('email', "%{$search}%");
});
})
->when($query->status === 'verified', fn (Builder $b) => $b->whereNotNull('email_verified_at'))
->when($query->status === 'unverified', fn (Builder $b) => $b->whereNull('email_verified_at'))
->when($query->role, fn (Builder $b, string $role) => $b->role($role))
->orderBy($query->sort, $query->direction)
->orderBy('id', $query->direction)
->paginate($query->perPage)
->withQueryString()
->through(fn (User $user): UserRowData => UserRowData::fromModel($user));
}
}
```
A few details are doing real work here:
- **The search is wrapped in its own `where()`.** Without the closure, `orWhereLike('email', ...)` would also escape the status and role filters.
- **`orderBy('id')` as a tie-breaker.** Sorting by `name` alone isn't stable when two users share a name, so rows can jump between pages.
- **`withQueryString()`** puts the current search, sort and filters into every pagination link. Without it, page 2 forgets the filters.
- **`with('roles:id,name')`** loads roles in one query instead of one per row. More on that in [fixing N+1 queries in Laravel](/blog/laravel-n-plus-one-queries.html).
- **`role()`** is the query scope from spatie/laravel-permission.
`UserRowData` is a spatie/laravel-data object with only the fields the table needs. Never send whole models to a table. It leaks columns, and it bloats every page response. If you generate TypeScript types from your Data classes, the Vue page gets a real `UserRowData` type for free. See [TypeScript types from PHP](/blog/laravel-typescript-types-from-php.html).
## A thin controller that returns the filters as props
```php
public function index(UserIndexRequest $request, UserTableService $users): Response
{
$query = $request->tableQuery();
return Inertia::render('users/Index', [
'users' => $users->paginate($query),
'filters' => $query->toArray(),
'roles' => $users->roleOptions(),
'stats' => Inertia::defer(fn () => $users->stats()),
]);
}
```
Returning `filters` matters more than it looks. When someone opens a shared link or refreshes, the page has to start with the same search text, sort and dropdown values that are in the URL. The server already validated them, so it's the right source. If this controller style is new to you, [thin controllers in Laravel](/blog/laravel-thin-controllers.html) explains the split.
## The Vue page: search, filters and sorting
Here's the script part. It keeps the form state locally and sends it to the server with `router.get()`:
```vue
```
`Paginated`, `UserRowData` and `UserFilters` are your own types (or generated ones). Each visit option has a reason:
| Option | Why we set it |
| --- | --- |
| `preserveState: true` | Keeps the component alive, so the search input doesn't lose focus while typing. `router.get()` defaults to `false`. |
| `preserveScroll: true` | The page doesn't jump to the top on every keystroke |
| `replace: true` | Typing "annie" doesn't add five entries to the browser history |
| `only: ['users', 'filters']` | A partial reload: the server skips `roles` and the deferred `stats` |
| `onStart` / `onFinish` | Drives the loading state |
Values set to `undefined` are left out of the query string, and so are defaults. That keeps URLs short and readable: `/users?search=ann` instead of a line full of `sort=created_at&direction=desc&per_page=10`.
We never send `page`. Any change to search, filters or sort starts again at page 1, which is what users expect. Staying on page 7 of a result set that now has two pages is a common bug in hand-built tables.
## The Vue template: headers, rows and pagination
```vue
{{ hasFilters ? 'No users match these filters.' : 'No users yet. Invite your first teammate.' }}
```
Laravel's paginator returns `links` with labels like `« Previous`, which is why the label goes through `v-html`. The labels come from Laravel's pagination translation strings, not from user input. The `links.length > 3` check hides the bar when there's only one page (previous, page 1, next).
## Accessible sortable headers
Most hand-built tables get this wrong, and it's cheap to fix:
- Put the click handler on a real `