kadevland/laravel-htmx-helpers 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

kadevland/laravel-htmx-helpers

Composer 安装命令:

composer require kadevland/laravel-htmx-helpers

包简介

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

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

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?

  • 🚀 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

  • PHP 8.2+
  • Laravel 11+ (for native @fragment directive support)

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

Request Macros

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

// 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

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

// 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

// 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)

// 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

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

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);
}
<!-- Blade template: users/edit.blade.php -->
@fragment('user-form')
    <form hx-put="/users/{{ $user->id }}" hx-target="#user-form" hx-swap="outerHTML">
        <!-- form fields -->
        <div class="success-message">User updated successfully!</div>
    </form>
@endfragment

Real-World Examples

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

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

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

// 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

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please report security vulnerabilities via email to contact@kadevland.net.

Credits

License

The MIT License (MIT). Please see License File for more information.

Related Packages

Why Not Use mauricius/laravel-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.

kadevland/laravel-htmx-helpers 适用场景与选型建议

kadevland/laravel-htmx-helpers 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 09 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「helpers」 「response」 「ajax」 「request」 「laravel」 「fragments」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 kadevland/laravel-htmx-helpers 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 kadevland/laravel-htmx-helpers 我们能提供哪些服务?
定制开发 / 二次开发

基于 kadevland/laravel-htmx-helpers 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 33
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-23