htmx with Laravel

htmx and Laravel fit because Laravel renders HTML. One route serves two shapes: the full page, or an @fragment piece through…

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>

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');
}

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

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:

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"]));
}

HX-Trigger for a toast, HX-Redirect to 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

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.

What you will learn