PHPackages                             kadevland/laravel-htmx-helpers - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. kadevland/laravel-htmx-helpers

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

kadevland/laravel-htmx-helpers
==============================

Native Laravel HTMX helpers for Request and Response objects - no external dependencies

v1.0.0(7mo ago)21MITPHPPHP ^8.2CI passing

Since Sep 23Pushed 7mo agoCompare

[ Source](https://github.com/kadevland/laravel-htmx-helpers)[ Packagist](https://packagist.org/packages/kadevland/laravel-htmx-helpers)[ RSS](/packages/kadevland-laravel-htmx-helpers/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (10)Versions (2)Used By (0)

Laravel HTMX Helpers
====================

[](#laravel-htmx-helpers)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d8249299cfa1f0890e4733434863a886112500e70db6752bdd4007ade2bb06d1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b616465766c616e642f6c61726176656c2d68746d782d68656c706572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kadevland/laravel-htmx-helpers)[![GitHub Tests Action Status](https://camo.githubusercontent.com/dfe43dfc2b56ca569e54be7abb7cb87b97995b875383220319cc91aa29bf73c4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6b616465766c616e642f6c61726176656c2d68746d782d68656c706572732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/kadevland/laravel-htmx-helpers/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/58e194ea8c72990cc6b707a0e5b51cf921020b6f638e9ac00e5d756bcb64ae7f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6b616465766c616e642f6c61726176656c2d68746d782d68656c706572732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/kadevland/laravel-htmx-helpers/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/6b68db3511a846e4672062ba4ceec57d1214f4be6c6abe9ea9eafb03b7a50a4c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6b616465766c616e642f6c61726176656c2d68746d782d68656c706572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kadevland/laravel-htmx-helpers)

Native Laravel HTMX helpers for Request and Response objects with **zero external dependencies**. This package provides a clean, Laravel-native way to work with HTMX without requiring any third-party HTMX packages.

Why This Package?
-----------------

[](#why-this-package)

- 🚀 **Zero Dependencies**: Uses only Laravel's native Request/Response macros
- 🧪 **Fully Tested**: Comprehensive Pest test suite
- 📚 **Well Documented**: Clear examples and use cases
- 🔧 **Framework Native**: Integrates seamlessly with Laravel 11+ (requires @fragment support)
- 🎯 **Type Safe**: Full TypeScript-style PHP declarations
- ⚡ **Lightweight**: Minimal overhead and performance impact

Requirements
------------

[](#requirements)

- **PHP 8.2+**
- **Laravel 11+** (for native `@fragment` directive support)

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require kadevland/laravel-htmx-helpers
```

The package will auto-register itself via Laravel's package discovery.

Optionally, you can publish the config file:

```
php artisan vendor:publish --tag="htmx-helpers-config"
```

Usage
-----

[](#usage)

### Request Macros

[](#request-macros)

#### Detecting HTMX Requests

[](#detecting-htmx-requests)

```
use Illuminate\Http\Request;

public function handle(Request $request)
{
    if ($request->isHtmxRequest()) {
        // Handle HTMX request
        return view('partial.content')->fragment('main-content');
    }

    // Handle regular request
    return view('full.page');
}
```

#### Getting HTMX Request Information

[](#getting-htmx-request-information)

```
// Check if request is boosted
if ($request->isHtmxBoosted()) {
    // Handle boosted request
}

// Get current URL from HTMX
$currentUrl = $request->htmxCurrentUrl();

// Check if it's a history restore request
if ($request->isHtmxHistoryRestoreRequest()) {
    // Handle history restore
}

// Get prompt response
$userInput = $request->htmxPrompt();

// Get target and trigger information
$target = $request->htmxTarget();        // "#main-content"
$trigger = $request->htmxTrigger();      // "#submit-button"
$triggerName = $request->htmxTriggerName(); // "my-trigger"
```

### Response Macros

[](#response-macros)

#### Basic HTMX Responses

[](#basic-htmx-responses)

```
use Illuminate\Support\Facades\Response;

// Redirect the browser
return Response::htmxRedirect('/dashboard');

// Refresh the current page
return Response::htmxRefresh();

// Push a new URL to browser history
return Response::htmxPushUrl('/new-url');

// Replace current URL in browser history
return Response::htmxReplaceUrl('/updated-url');
```

#### Advanced HTMX Responses

[](#advanced-htmx-responses)

```
// Client-side location (can include additional data)
return Response::htmxLocation([
    'path' => '/users',
    'target' => '#main-content',
    'swap' => 'innerHTML'
]);

// Override swap method
return Response::htmxReswap('outerHTML');

// Override target element
return Response::htmxRetarget('#different-target');

// Override selector
return Response::htmxReselect('.new-selector');
```

#### Event Triggering

[](#event-triggering)

```
// Trigger single event
return Response::htmxTrigger('userUpdated');

// Trigger multiple events with data
return Response::htmxTrigger([
    'userUpdated' => ['id' => 123],
    'showNotification' => 'User saved successfully'
]);

// Trigger events after settle
return Response::htmxTriggerAfterSettle('dataLoaded');

// Trigger events after swap
return Response::htmxTriggerAfterSwap('contentSwapped');
```

#### Multiple Fragments (Out-of-Band Swaps)

[](#multiple-fragments-out-of-band-swaps)

```
// Send multiple fragments in one response using Laravel native methods
return view('admin.users.index', compact('users', 'stats'))
    ->fragments(['user-list', 'user-stats', 'notifications']);

// Or conditionally send fragments
return view('admin.users.index', compact('users', 'stats'))
    ->fragmentsIf($request->isHtmxRequest(), ['user-list', 'user-stats']);
```

#### Polling Control

[](#polling-control)

```
// Stop HTMX polling (returns 286 status code)
return Response::htmxStopPolling();
```

Laravel Blade Integration
-------------------------

[](#laravel-blade-integration)

This package works seamlessly with Laravel 11+'s native `@fragment` directive:

```
// Controller
public function update(Request $request, User $user)
{
    $user->update($request->validated());

    if ($request->isHtmxRequest()) {
        return response(
            view('users.edit', compact('user'))->fragment('user-form')
        );
    }

    return redirect()->route('users.show', $user);
}
```

```

@fragment('user-form')

        User updated successfully!

@endfragment
```

Real-World Examples
-------------------

[](#real-world-examples)

### 1. Form Submission with Validation

[](#1-form-submission-with-validation)

```
public function store(CreateUserRequest $request)
{
    try {
        $user = User::create($request->validated());

        if ($request->isHtmxRequest()) {
            return response(
                view('users.create', [
                    'message' => 'User created successfully!',
                    'user' => $user
                ])->fragment('form-response')
            );
        }

        return redirect()->route('users.index')
            ->with('success', 'User created!');

    } catch (ValidationException $e) {
        if ($request->isHtmxRequest()) {
            return response(
                view('users.create', [
                    'errors' => $e->errors()
                ])->fragment('form-errors'),
                422
            );
        }

        return back()->withErrors($e->errors())->withInput();
    }
}
```

### 2. Dynamic Content Loading

[](#2-dynamic-content-loading)

```
public function loadUserPosts(Request $request, User $user)
{
    $posts = $user->posts()->paginate(10);

    // Using Laravel's native fragmentIf method
    return view('users.show', compact('user', 'posts'))
        ->fragmentIf($request->isHtmxRequest(), 'posts-list');
}
```

### 3. Search with Live Results

[](#3-search-with-live-results)

```
public function search(Request $request)
{
    $query = $request->get('q');
    $results = User::where('name', 'like', "%{$query}%")->get();

    // Using Laravel's native fragmentIf method
    return view('search.index', compact('results'))
        ->fragmentIf($request->isHtmxRequest(), 'search-results');
}
```

Configuration
-------------

[](#configuration)

```
// config/htmx-helpers.php
return [
    'enabled' => env('HTMX_HELPERS_ENABLED', true),

    'headers' => [
        'default_swap' => 'innerHTML',
        'auto_csrf' => env('HTMX_AUTO_CSRF', true),
    ],

    'debug' => [
        'log_requests' => env('HTMX_LOG_REQUESTS', false),
        'debug_headers' => env('HTMX_DEBUG_HEADERS', false),
    ],
];
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please report security vulnerabilities via email to .

Credits
-------

[](#credits)

- [kadevland](https://github.com/kadevland)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

Related Packages
----------------

[](#related-packages)

- [mauricius/laravel-htmx](https://github.com/mauricius/laravel-htmx) - Full-featured HTMX package for Laravel

Why Not Use mauricius/laravel-htmx?
-----------------------------------

[](#why-not-use-mauriciuslaravel-htmx)

The `mauricius/laravel-htmx` package is excellent, but this package offers:

1. **Zero Dependencies**: No external package dependencies
2. **Laravel Native**: Uses only Laravel's macro system
3. **Lightweight**: Minimal footprint
4. **Framework Integration**: Designed specifically for Laravel 11+ features (native @fragment support)
5. **Simplicity**: Just the macros you need, nothing more

Choose this package if you want a minimal, dependency-free solution. Choose `mauricius/laravel-htmx` if you need advanced HTMX features like middleware, validation helpers, etc.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance62

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

231d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f9789c85320e3dfb98dfedffa61765104826b5c8e5483bb5d8d520688756f411?d=identicon)[kadevland](/maintainers/kadevland)

---

Top Contributors

[![kadevland](https://avatars.githubusercontent.com/u/1887658?v=4)](https://github.com/kadevland "kadevland (1 commits)")

---

Tags

responserequestlaravelhelpersajaxhtmxfragments

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/kadevland-laravel-htmx-helpers/health.svg)

```
[![Health](https://phpackages.com/badges/kadevland-laravel-htmx-helpers/health.svg)](https://phpackages.com/packages/kadevland-laravel-htmx-helpers)
```

###  Alternatives

[watson/active

Laravel helper for recognising the current route, controller and action

3253.6M14](/packages/watson-active)[erlandmuchasaj/laravel-gzip

Gzip your responses.

40129.3k2](/packages/erlandmuchasaj-laravel-gzip)[glhd/conveyor-belt

14797.0k](/packages/glhd-conveyor-belt)[dragon-code/pretty-routes

Pretty Routes for Laravel

10058.7k4](/packages/dragon-code-pretty-routes)[bjuppa/laravel-blog

Add blog functionality to your Laravel project

483.3k2](/packages/bjuppa-laravel-blog)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
