Laravel Htmx

Last updated on by

Laravel Htmx image

Laravel htmx is a package by Maurizio Bonani that gives you a nice way of working with htmx, a library that allows you to access modern browser features directly from HTML, rather than using JavaScript:

htmx gives you access to AJAX, CSS Transitions, WebSockets and Server Sent Events directly in HTML, using attributes, so you can build modern user interfaces with the simplicity and power of hypertext

htmx is small (~14k min.gz’d), dependency-free, extendable, IE11 compatible & has reduced code base sizes by 67% when compared with react

Let's look at the features the Laravel htmx package outlines in their readme:

Htmx Request

You can resolve an instance of the HtmxRequest from the container which provides shortcuts for reading the htmx-specific request headers.

use Mauricius\LaravelHtmx\Http\HtmxRequest;
 
Route::get('/', function (HtmxRequest $request)
{
// always true if the request is performed by Htmx
$request->isHtmxRequest();
// indicates that the request is via an element using hx-boost
$request->isBoosted();
// the current URL of the browser
$request->getCurrentUrl();
// true if the request is for history restoration after a miss in the local history cache
$request->isHistoryRestoreRequest()
// the user response to an hx-prompt
$request->getPromptResponse();
// the id of the target element if it exists
$request->getTarget();
// the name of the triggered element if it exists
$request->getTriggerName();
// the id of the triggered element if it exists
$request->getTriggerId();
});

Htmx Response

  • HtmxResponseClientRedirect

htmx can trigger a client side redirect when it receives a response with the HX-Redirect header. The HtmxResponseClientRedirect makes it easy to trigger such redirects.

use Mauricius\LaravelHtmx\Http\HtmxResponseClientRedirect;
 
Route::get('/', function (HtmxRequest $request)
{
return new HtmxResponseClientRedirect('/somewhere-else');
});
  • HtmxResponseClientRefresh

htmx will trigger a page reload when it receives a response with the HX-Refresh header. HtmxResponseClientRefresh is a custom response class that allows you to send such a response. It takes no arguments, since htmx ignores any content.

use Mauricius\LaravelHtmx\Http\HtmxResponseClientRefresh;
 
Route::get('/', function (HtmxRequest $request)
{
return new HtmxResponseClientRefresh();
});
  • HtmxResponseStopPolling

When using a polling trigger, htmx will stop polling when it encounters a response with the special HTTP status code 286. HtmxResponseStopPolling is a custom response class with that status code.

use Mauricius\LaravelHtmx\Http\HtmxResponseStopPolling;
 
Route::get('/', function (HtmxRequest $request)
{
return new HtmxResponseStopPolling();
});

For all the remaining available headers you can use the HtmxResponse class.

use Mauricius\LaravelHtmx\Http\HtmxResponse;
 
Route::get('/', function (HtmxRequest $request)
{
return with(new HtmxResponse())
->location($location) // Allows you to do a client-side redirect that does not do a full page reload
->pushUrl($url) // pushes a new url into the history stack
->replaceUrl($url) // replaces the current URL in the location bar
->reswap($option) // Allows you to specify how the response will be swapped
->retarget($selector); // A CSS selector that updates the target of the content update to a different element on the page
});

Additionally, you can trigger client-side events using the addTrigger method.

use Mauricius\LaravelHtmx\Http\HtmxResponse;
 
Route::get('/', function (HtmxRequest $request)
{
return with(new HtmxResponse())
->addTrigger($event)
->addTriggerAfterSettle($event)
->addTriggerAfterSwap($event);
});

You can call those methods multiple times to trigger multiple events.

Render Blade Fragments with Htmx

This library also provides a basic Blade extension to render template fragments.

The library provides two new Blade directives: @fragment and @endfragment. You can use these directives to specify a block of content within a template and render just that bit of content. For instance:

{{-- /contacts/detail.blade.php --}}
<html>
<body>
<div hx-target="this">
@fragment("archive-ui")
@if($contact->archived)
<button hx-patch="/contacts/{{ $contact->id }}/unarchive">Unarchive</button>
@else
<button hx-delete="/contacts/{{ $contact->id }}">Archive</button>
@endif
@endfragment
</div>
<h3>Contact</h3>
<p>{{ $contact->email }}</p>
</body>
</html>

With this fragment defined in our template, we can now render either the entire template:

Route::get('/', function ($id) {
$contact = Contact::find($id);
 
return View::make('contacts.detail', compact('contact'));
});

Or we can render only the archive-ui fragment of the template by using the renderFragment macro defined in the \Illuminate\View\View class:

Route::patch('/contacts/{id}/unarchive', function ($id) {
$contact = Contact::find($id);
 
// The following approaches are equivalent
 
// Using the View Facade
return \Illuminate\Support\Facades\View::renderFragment('contacts.detail', 'archive-ui', compact('contact'));
 
// Using the view() helper
return view()->renderFragment('contacts.detail', 'archive-ui', compact('contact'));
 
// Using the HtmxResponse Facade
return \Mauricius\LaravelHtmx\Facades\HtmxResponse::renderFragment('contacts.detail', 'archive-ui', compact('contact'));
 
// Using the HtmxResponse class
return with(new \Mauricius\LaravelHtmx\Http\HtmxResponse())
->renderFragment('contacts.detail', 'archive-ui', compact('contact'));
});

OOB Swap support

htmx supports updating multiple targets by returning multiple partial responses with hx-swap-oop. With this library you can return multiple fragments by using the HtmxResponse as a return type.

For instance, let's say that we want to mark a todo as completed using a PATCH request to /todos/{id}. With the same request, we also want to update in the footer how many todos are left:

{{-- /todos.blade.php --}}
<html>
<body>
<main hx-target="this">
<section>
<ul class="todo-list">
@fragment("todo")
<li id="todo-{{ $todo->id }}" @class(['completed' => $todo->done])>
<input
type="checkbox"
class="toggle"
hx-patch="/todos/{{ $todo->id }}"
@checked($todo->done)
hx-target="#todo-{{ $todo->id }}"
hx-swap="outerHTML"
/>
{{ $todo->name }}
</li>
@endfragment
</ul>
</section>
<footer>
@fragment("todo-count")
<span id="todo-count" hx-swap-oob="true">
<strong>{{ $left }} items left</strong>
</span>
@endfragment
</footer>
</main>
</body>
</html>

We can use the HtmxResponse to return multiple fragments:

Route::patch('/todos/{id}', function ($id) {
$todo = Todo::find($id);
$todo->done = !$todo->done;
$todo->save();
 
$left = Todo::where('done', 0)->count();
 
return HtmxResponse::addFragment('todomvc', 'todo', compact('todo'))
->addFragment('todomvc', 'todo-count', compact('left'));
});

Find out more about the Laravel htmx package on GitHub.

Eric L. Barnes photo

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Streamlining Route Parameters in Laravel Using URL Defaults image

Streamlining Route Parameters in Laravel Using URL Defaults

Read article
Flexible Docker Images with PHP INI Environment Variables image

Flexible Docker Images with PHP INI Environment Variables

Read article
Dynamic Form Validation in Laravel with prohibited_if image

Dynamic Form Validation in Laravel with prohibited_if

Read article
Add Approvals to Your Laravel Application image

Add Approvals to Your Laravel Application

Read article
Enhancing Data Processing with Laravel's transform() Method image

Enhancing Data Processing with Laravel's transform() Method

Read article
Get Xdebug Working With Docker and PHP 8.4 in One Minute image

Get Xdebug Working With Docker and PHP 8.4 in One Minute

Read article