Laravel with HTMX: The Blade Partial API Pattern
Raheel Shan
October 19th, 2025 · 9 min read
To use HTMX with Laravel, return a Blade partial from a Laravel route and let HTMX swap it into the page. The browser never builds markup from JSON, there is no build step, and the first page load is full server-rendered HTML that search engines can read. This post shows the pattern with working code, the rules that keep it tidy, and the security checks it needs before production.
Quick answer
- Render the full page with Blade, and use
@includefor the parts that will refresh. - Add
hx-get,hx-targetandhx-swapto a button or link, pointing at the partial's URL. - Serve every partial from one route that turns the URL into a view name and returns the rendered HTML.
How Laravel and HTMX work together
HTMX is a small JavaScript library that adds attributes to HTML. hx-get says which URL to request, hx-target says which element to update, and hx-swap says how to put the response in. The server answers with an HTML fragment, not JSON. Laravel already knows how to render fragments: they are Blade partials.
Load HTMX once in your layout:
<script src="https://unpkg.com/[email protected]"></script>
Step 1: Load the full page with Blade
We will show a table of products, where each row has a Refresh button. The controller is plain Laravel.
class ProductController extends Controller
{
public function index(Request $request)
{
$products = Product::paginate(10);
return view('product.index', compact('products'));
}
}
The page view includes a partial inside the loop:
{{-- resources/views/product/index.blade.php --}}
@extends('layouts.app')
@section('content')
<div class="container">
<h2>Products</h2>
<table>
<thead>
<tr>
<th scope="col">Product</th>
<th scope="col">Category</th>
<th scope="col">Brand</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
@foreach ($products as $product)
@include('product.partials.table.row', ['product' => $product])
@endforeach
</tbody>
</table>
</div>
@endsection
Step 2: Make the row refreshable with HTMX
The row partial carries the HTMX attributes. Each row has a unique id, and the button asks for that row's partial and replaces the whole row.
{{-- resources/views/product/partials/table/row.blade.php --}}
<tr id="product-{{ $product->id }}">
<td>{{ $product->name }}</td>
<td>{{ $product->category }}</td>
<td>{{ $product->brand }}</td>
<td>
<button
type="button"
hx-get="{{ url('product/partials/table/row/'.$product->id) }}"
hx-target="#product-{{ $product->id }}"
hx-swap="outerHTML"
class="btn btn-sm btn-primary">
Refresh
</button>
</td>
</tr>
The same partial is used for the first page load and for every refresh. That is the whole idea: no second template, no JSON shape to keep in sync.
Step 3: One route for every partial
Instead of writing a route per partial, one route turns the URL into a view name: product/partials/table/row/5 renders product.partials.table.row for product 5.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Str;
Route::match(['get', 'post'], '{path}', function (string $path, Request $request) {
// Only HTMX requests, and only safe characters
abort_unless($request->header('HX-Request') === 'true', 404);
abort_unless(preg_match('#^[A-Za-z0-9_\-/]+$#', $path), 404);
// Only views that live in a "partials" folder
abort_unless(str_contains($path, 'partials/'), 404);
// product/partials/table/row/5 -> view + id
$segments = explode('/', $path);
$id = is_numeric(end($segments)) ? array_pop($segments) : null;
$view = implode('.', $segments);
abort_unless(View::exists($view), 404);
// Load a model only when you have listed it
$allowed = [\App\Models\Product::class];
$modelClass = 'App\\Models\\'.Str::studly(Str::singular($segments[0]));
$data = [];
if ($id !== null && in_array($modelClass, $allowed, true)) {
$data[Str::camel(class_basename($modelClass))] = $modelClass::findOrFail($id);
}
return view($view, $data);
})->where('path', '.*');
Register it last in routes/web.php, so your normal routes win.
Refresh a whole table
The same route handles a table refresh. Put the rows in their own partial and target the table body:
<button
type="button"
hx-get="{{ url('product/partials/table/list') }}"
hx-target="#product-rows"
hx-swap="innerHTML">
Refresh table
</button>
<tbody id="product-rows">
@include('product.partials.table.list', ['products' => $products])
</tbody>
The list partial loops over the products and includes the row partial. For a list, pass the data from the page, or add a model to $allowed and load the collection yourself.
The rules
- Directory equals URL.
/product/partials/formmaps toresources/views/product/partials/form.blade.php. - Dots replace slashes. The route turns
/into.for Laravel's view names. - Any depth. Nested folders work:
product/partials/table/row. - Missing partial means 404. No silent fallbacks.
- GET and POST. The same route answers
hx-get,hx-postand form submits. - Only
partials/. Nothing outside a partials folder can be requested. - Data is opt-in. A model is loaded only when it is on your allowed list.
Lock it down before production
The first version of this pattern, which rendered any view and loaded any model by URL, is fine for a demo and unsafe in a real app. Anything the route can reach, a visitor can request. Keep these four checks:
- Restrict to a
partials/folder, so layouts, emails and admin views can never be rendered by URL. - Check the
HX-Requestheader. HTMX sends it on every request. It is not security by itself, but it keeps the route from being a public page. - Never auto-load models by name. Use an allowed list, and add
authorizeor a policy check for the model you load. - Add middleware to the route. Put
auth, throttling or your gates on the route or a group. For POST requests, send the CSRF token withhx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'on the body.
Every request still goes through Laravel's middleware, validation and gates, so a partial can be protected exactly like an API route. The difference is that the response is markup, not JSON.
How this keeps your pages SEO-friendly
On the first visit Laravel returns a complete HTML document with every partial in place, so crawlers see all the content. HTMX only takes over after the page has loaded, reusing the same Blade partials. A client-rendered app starts with an empty div and asks crawlers to run JavaScript before there is anything to index.
Laravel with HTMX vs Livewire vs a JS framework
- HTMX: a small attribute-based library, no server component classes, you write routes and Blade. Best when you want plain HTML and full control.
- Livewire: PHP components with state kept in sync with the browser. More features, more moving parts. See how Livewire works under the hood, or HTMX vs Livewire for the same feature built both ways.
- React or Vue: a build pipeline, JSON endpoints and a client-side renderer. Worth it for highly interactive apps, heavy for admin tables and forms.
If you want to see how far plain Laravel can go, read Livewire without Livewire, Inertia without Inertia, GraphQL without GraphQL. For loading real data into partials, continue with the Blade Partial API Pattern: Fetching Data. If you are new to HTMX, the Laravel HTMX tutorial walks through the first steps.
FAQ
Can I use HTMX with Laravel? Yes. Return a Blade partial from a Laravel route and point hx-get at it. No package is required.
Do I need Livewire if I use HTMX? No. They solve similar problems differently. HTMX swaps server-rendered HTML; Livewire keeps PHP component state in sync.
Is a global partial route safe? Only with limits: restrict it to a partials/ folder, check the HX-Request header, allow only listed models and add middleware.
Does HTMX hurt SEO? No. The first response is full HTML, so crawlers see the content. HTMX updates happen after load.
How do I send a POST request with HTMX in Laravel? Use hx-post and include the CSRF token in hx-headers, or inside the form with @csrf.
Build the interactive parts without React
Live search, tables and forms on server-rendered HTML, with HTMX or jsRibbon and no build step.
Bring the page you want to make interactive and we build the first piece together in 60 minutes.
Found this useful?
Support the work that goes into these posts.