Your Laravel /board route already answers with a full page from Blade. Now polling and the htmx form call the same route, and all they need is the board piece. A second route and a second view? No need.
Laravel renders HTML with Blade, and htmx only asks for HTML. So Mrs. Rini's order board can be served by Laravel as it is: the same routes, the same views, only the shape of the reply adapts. It's like Mrs. Rini's regular print shop. For a new customer, the shop sends the full brochure: cover, list of services, every page. If the cashier only asks for the new price page, the shop sends that one sheet, from the same printing plate. Laravel is the print shop, Blade is the plate, and the HX-Request: true header on the request is the note saying "one sheet is enough".
Routes and layout
// routes/web.php
use App\Http\Controllers\BoardController;
use Illuminate\Support\Facades\Route;
Route::get('/board', [BoardController::class, 'index'])->name('board');
Route::post('/order', [BoardController::class, 'store'])->name('order.store');
Route::post('/close-books', [BoardController::class, 'closeBooks'])->name('close-books');
Route::view('/report', 'report')->name('report');
{{-- resources/views/layouts/app.blade.php --}}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>@yield('title') | Mrs. Rini's Laundry</title>
<meta name="htmx-config" content='{"responseHandling":[{"code":"204","swap":false},{"code":"[23]..","swap":true},{"code":"422","swap":true,"error":true},{"code":"[45]..","swap":false,"error":true}]}'>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body hx-boost="true" hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
hx-on:toast="document.getElementById('toast').textContent = event.detail.value">
<nav>
<a href="/board">Board</a> <a href="/report">Report</a> <a href="/prices">Prices</a>
</nav>
<main id="content">
@yield('content')
</main>
<p id="toast" role="status"></p>
</body>
</html>
- htmx routes go in
routes/web.php, notapi.php: web routes have the session, cookies and CSRF protection. hx-boost="true"on<body>makes every link in<nav>go through htmx. Laravel still renders the full page, htmx swaps the<body>content, and<head>isn't loaded again.htmx-configallows 422 replies to swap (covered in the validation section),hx-headerscarries the CSRF token, andhx-on:toastshows a notice from the server.
One view, two shapes: @fragment
{{-- resources/views/board/index.blade.php --}}
@extends('layouts.app')
@section('title', 'Order board')
@section('content')
<h1>Order board · <span id="active-count">{{ $orders->count() }} active orders</span></h1>
<button hx-get="/board" hx-target="#order-board" hx-swap="outerHTML">Reload board</button>
@fragment('board')
<ul id="order-board" hx-get="/board" hx-trigger="every 30s" hx-swap="outerHTML">
@foreach ($orders as $order)
@include('board._row', ['order' => $order])
@endforeach
</ul>
@endfragment
@include('board._form')
<button hx-post="/close-books">Close the books</button>
@endsection
public function index(Request $request): Response
{
$orders = Order::orderBy('id')->get();
$fragmentOnly = $request->hasHeader('HX-Request') && ! $request->hasHeader('HX-Boosted');
return response(view('board.index', ['orders' => $orders])->fragmentIf($fragmentOnly, 'board'))
->header('Vary', 'HX-Request');
}
$request->header('HX-Request')reads that header's value, which is"true", ornullwhen it's missing.$request->hasHeader('HX-Request')answerstrueorfalse.fragmentIf($fragmentOnly, 'board')renders the view, but only sends what's between@fragment('board')and@endfragment. With no condition:->fragment('board'). For several at once:fragments([...]).- The result is lighter and faster. In the Lab, the full page is 1,486 bytes and the
boardpiece 346 bytes. In a real app, the gap is far bigger. Vary: HX-Requesttells caches (the browser or a CDN) that one address has two shapes. Without it, a cache may serve the polling piece as the/boardpage.
hx-boost carries HX-Request too
A boosted link is sent by htmx, so it carries HX-Request: true too, plus HX-Boosted: true. If the controller only checks HX-Request, clicking Board in the menu gets the <ul> piece, and htmx swaps the whole <body> content for that list: the menu, heading and form are gone. That's why the condition is hasHeader('HX-Request') && ! hasHeader('HX-Boosted'): a boosted link still gets the full page.
CSRF: a token on every request
- POST, PUT, PATCH and DELETE requests go through the
PreventRequestForgerymiddleware (Laravel 13). It lets a request through when itsSec-Fetch-Siteheader issame-origin. That header isn't always sent (old browsers, addresses that aren't HTTPS), and then the token is checked: the_tokenfield or theX-CSRF-TOKENheader. hx-headerson<body>is inherited by every element, sohx-postorhx-deletebuttons outside a form carry the token too.- Forms keep
@csrf(the hidden_tokeninput), so they still work without JavaScript. - A wrong or missing token: 419 Page Expired, which htmx doesn't swap. The button just seems not to react.
Content from users and hx-* attributes. Besides CSRF, there is one more gap. htmx reads hx-* attributes in any HTML that enters the page, including text that people type, such as a customer's name. If that text is printed raw, htmx also runs the hx-* attributes inside it. Three safeguards:
- Print content from users with
{{ $order->name }}, not{!! $order->name !!}. Blade turns{{ }}intoe(), which writes<as<, so the tags and attributes show as plain text. - If HTML from users really has to show (cleaned by a sanitizer, a library that removes dangerous tags and attributes), wrap it in
hx-disable:<div hx-disable>{!! $cleanNote !!}</div>. In Chromium with htmx 2.0.11, no request came from inside it, not even from an element inside that sayshx-disable="false". In htmx 4, this attribute is namedhx-ignore. htmx.config.selfRequestsOnlyistrueby default: htmx sends requests only to the page's own domain. Leave it that way.
Validation fails: a 422 into the form
htmx doesn't send X-Requested-With, so to Laravel the request isn't AJAX. A failing $request->validate() answers 302 to the previous page. The XHR follows that redirect quietly (the HX-Request header comes along), htmx gets the board piece with a 200 status, and sticks it at the end of the board: a doubled board, and the error message never shows. Handle it yourself:
public function store(Request $request): Response|RedirectResponse
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:50'],
'weight' => ['required', 'numeric', 'min:1', 'max:30'],
], ['weight.max' => 'The maximum weight is :max kg.']);
if ($validator->fails() && $request->hasHeader('HX-Request')) {
$request->flash();
return response(view('board._form')->withErrors($validator), 422)
->header('HX-Retarget', '#intake')
->header('HX-Reswap', 'outerHTML');
}
$order = Order::create([...$validator->validate(), 'status' => 'Queued']);
if (! $request->hasHeader('HX-Request')) {
return redirect()->route('board');
}
return response(view('board._new-order', ['order' => $order, 'active' => Order::count()]))
->header('HX-Trigger', json_encode(['toast' => "Order #{$order->id} received"]));
}
- For an htmx request, the form is sent back with 422.
$request->flash()fillsold('name')in the partial, andwithErrors()makes@error('weight')show "The maximum weight is 30 kg.". HX-Retarget: #intakeandHX-Reswap: outerHTMLmake the form the thing that's swapped, not the board. htmx only swaps that 422 because the layout allows it throughhtmx-config. Another way: the[email protected]extension withhx-ext="response-targets"andhx-target-422, which still uses the form's ownhx-swap.- Without JavaScript,
$validator->validate()throws, and Laravel does what it always does: redirect back with the errors and the input. board/_new-order.blade.phpholds the new row,<span id="active-count" hx-swap-oob="true">, and an empty form withhx-swap-oob="true", like the success reply in the board project.
HX-Trigger for a toast, HX-Redirect to change page
HX-Trigger: {"toast":"Order #15 received"}fires atoastevent on the form that sent the request. The event bubbles up to<body>, andhx-on:toastwritesevent.detail.valueinto#toast.redirect()->route('report')from an htmx request is followed quietly by the XHR, so the report page is put into the button's target. To really change page:
public function closeBooks(): Response
{
return response()->noContent()->header('HX-Redirect', route('report'));
}
📌 A helper package (optional)
composer require mauricius/laravel-htmx (v0.10, for Laravel 12 and 13) gives you HtmxRequest with isHtmxRequest() and isBoosted(), plus reply classes such as HtmxResponseClientRedirect. Everything above can still be written without this package.
⚠️ A layout inside the target, and a piece served to a link
- Answering every htmx request with the full page. The whole layout lands inside the target. Use
@fragmentandfragmentIf. - Checking only
HX-Request. Boosted links get the piece too. Add! $request->hasHeader('HX-Boosted'). $request->validate()orredirect()for an htmx request. The redirect is followed quietly by the XHR. Answer with a 422 andHX-Retarget, or withHX-Redirect.hx-booston an element that doesn't wrap its links. In the exercise,hx-boost="true"goes on<body>, with the value exactlytrue, and the three links in<nav>sit inside it, together with<main id="content">. The same<body>also carrieshx-headerswithX-CSRF-TOKEN.
TL;DR: htmx and Laravel fit because Laravel renders HTML. One route serves two shapes: the full page, or an @fragment piece through view(...)->fragmentIf($request->hasHeader('HX-Request') && ! $request->hasHeader('HX-Boosted'), 'board'), plus Vary: HX-Request. $request->header('HX-Request') reads the header, and the piece is lighter and faster (1,486 bytes down to 346 in the Lab). hx-boost="true" on <body> moves between pages without a reload, with HX-Boosted: true. The CSRF token travels in hx-headers as X-CSRF-TOKEN: with no token and no Sec-Fetch-Site: same-origin, the reply is 419. A failed validation answers 422 with the form, HX-Retarget and HX-Reswap, which swaps because htmx-config allows it. HX-Trigger fires a toast, and HX-Redirect moves the browser, because a plain redirect() is followed quietly by the XHR. Print content from users with {{ }}, so htmx doesn't run the hx-* attributes inside it.
⚡ One view, two shapes
Write:
public function index(Request $request): Response
{
$orders = Order::orderBy('id')->get();
$fragmentOnly = $request->hasHeader('HX-Request') && ! $request->hasHeader('HX-Boosted');
return response(view('board.index', ['orders' => $orders])->fragmentIf($fragmentOnly, 'board'))
->header('Vary', 'HX-Request');
}
Guess first: for an htmx request, the controller answers with an @fragment piece instead of the full page. What's the gain?
The reply is lighter and faster. In the Lab, the full page is 1,486 bytes, and the board piece only 346 bytes.
Meaning: fragmentIf renders the view, but only sends what's inside @fragment('board'). Vary: HX-Request tells caches that one address has two shapes.
⚡ Boosted links carry HX-Request too
Meaning: A boosted link sends HX-Request: true plus HX-Boosted: true. If the controller only checks HX-Request, a menu click gets the <ul> piece, and the whole <body> content is swapped for that list. That's why the condition adds ! hasHeader('HX-Boosted').
⚡ The CSRF token, then HX-Redirect
Write:
<body hx-boost="true" hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
Meaning: hx-headers on <body> is inherited, so every htmx request carries the token. Without it, the reply is 419 and the button seems not to react. To change page, use HX-Redirect, because a plain redirect() is followed quietly by the XHR.