PHPackages                             nuimarkets/laravel-shared-utils - 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. nuimarkets/laravel-shared-utils

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

nuimarkets/laravel-shared-utils
===============================

Common Laravel Classes

0.3.2(1mo ago)13.0k↓33.3%[1 PRs](https://github.com/nuimarkets/nui-laravel-shared-utils/pulls)MITPHPPHP ^8.2CI passing

Since Jan 12Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/nuimarkets/nui-laravel-shared-utils)[ Packagist](https://packagist.org/packages/nuimarkets/laravel-shared-utils)[ RSS](/packages/nuimarkets-laravel-shared-utils/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (19)Versions (76)Used By (0)

Laravel Shared Utilities
========================

[](#laravel-shared-utilities)

[![Latest Version](https://camo.githubusercontent.com/587caab45c14969d46d5be138bcb9c27c2448567e5274e9c8464af2519bb5531/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6e75696d61726b6574732f6c61726176656c2d7368617265642d7574696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nuimarkets/laravel-shared-utils)[![PHP Version](https://camo.githubusercontent.com/7cda96433e4f721c2dde0764271d0c5566e8e53c1a3b87ff07b3b14ff24c4eab/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6e75696d61726b6574732f6c61726176656c2d7368617265642d7574696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nuimarkets/laravel-shared-utils)[![Laravel Version](https://camo.githubusercontent.com/9165431a3b1e0f4a01a6cc9a6dbeaf9a93e342c032467fd4f7376be92383664e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d382e78253230253743253230392e7825323025374325323031302e782d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://laravel.com)[![Tests](https://camo.githubusercontent.com/f231662810395e92a1764e6939786c377d223c224cccf730d588f4d7dd3b02e4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6e75696d61726b6574732f6e75692d6c61726176656c2d7368617265642d7574696c732f74657374732e796d6c3f6272616e63683d6d6173746572266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/nuimarkets/nui-laravel-shared-utils/actions)[![License](https://camo.githubusercontent.com/f78c35e80b571dc8b90a57ad644eb70cfa54c10ff1640a8b05f10a105cbb0769/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6e75696d61726b6574732f6c61726176656c2d7368617265642d7574696c732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/nuimarkets/laravel-shared-utils)

A comprehensive Laravel package providing standardized components for building robust microservice architectures. Battle-tested in production environments handling millions of requests.

Quick Start
-----------

[](#quick-start)

```
composer require nuimarkets/laravel-shared-utils
```

```
// Enable complete request lifecycle logging in 2 minutes
class ServiceRequestLogger extends RequestLoggingMiddleware {
    protected function getServiceName(): string {
        return 'my-service'; // Your service name
    }

    protected function addServiceContext($request, $context) {
        $context['resource_id'] = $request->route('id');
        return $context;
    }
}
// Register as global middleware → Automatic request start/complete + X-Ray correlation + performance metrics

// Add comprehensive health checks instantly
Route::get('/healthcheck', [HealthCheckController::class, 'detailed']);
```

Key Features
------------

[](#key-features)

### **Request Lifecycle Logging**

[](#request-lifecycle-logging)

Complete request tracking with automatic performance metrics, X-Ray trace correlation, and customizable service context. One middleware class gives you request start/complete logs, duration tracking, memory usage, and business logic correlation.

### **Distributed Tracing**

[](#distributed-tracing)

Native AWS X-Ray integration with automatic trace propagation across microservices. Track requests through your entire service mesh with zero configuration. Automatic response headers (`X-Request-ID` and `X-Trace-ID`) for frontend correlation.

### **Advanced Logging**

[](#advanced-logging)

Production-ready logging with automatic Elasticsearch routing, configurable sensitive data redaction, and structured JSON formatting. Fixes common logging issues that cause logs to end up in wrong indexes. Supports privacy compliance with flexible field-level redaction controls.

### **Health Monitoring**

[](#health-monitoring)

Comprehensive health checks for MySQL, PostgreSQL, Redis, storage, cache, and PHP environment. Get detailed diagnostics with a single endpoint.

### **Service Communication**

[](#service-communication)

Enhanced RemoteRepository with lazy token loading for optimal performance, retry logic, automatic JWT authentication, and proper HTTP status propagation.

### **Failure Caching**

[](#failure-caching)

Intelligent caching of remote service failures to prevent cascading timeouts during outages. HTTP status-aware TTLs cache 404s longer than transient errors like timeouts. Includes failure classification, configurable per-category TTLs, and convenience methods for handling cached failures gracefully.

### **Analytics Integration**

[](#analytics-integration)

Complete Intercom integration for user analytics and event tracking with queue-based processing and multi-tenant support.

### **JSON API Validation**

[](#json-api-validation)

Standardized JSON:API error handling with consistent validation responses. Provides unified error formatting across all services without configuration.

### **Testing Utilities**

[](#testing-utilities)

Automated test database management, specialized test jobs for queue testing, JSON API validation assertions, and base test cases for rapid test development.

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

[](#requirements)

- PHP 8.0 or higher
- Laravel 8.x, 9.x, or 10.x
- Composer 2.x

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

[](#installation)

```
composer require nuimarkets/laravel-shared-utils
```

### Optional Configuration Publishing

[](#optional-configuration-publishing)

```
# Publish all configs
php artisan vendor:publish --provider="NuiMarkets\LaravelSharedUtils\Providers\LoggingServiceProvider"

# Publish specific configs
php artisan vendor:publish --tag=logging-utils-config
php artisan vendor:publish --tag=intercom-config
```

Documentation
-------------

[](#documentation)

### Core Components

[](#core-components)

ComponentDescriptionDocumentation**Distributed Tracing**AWS X-Ray integration with request correlation[Guide](docs/distributed-tracing.md)**Logging System**Enhanced logging with Elasticsearch routing[Guide](docs/logging-integration.md)**RemoteRepository**Service-to-service communication framework[Guide](docs/RemoteRepository.md)**Failure Caching**Cache remote failures to prevent cascading timeouts[Guide](docs/failure-caching.md)**JSON API Validation**Standardized error handling with unified formatting[Guide](docs/json-api-validation.md)**Intercom Integration**User analytics and event tracking[Guide](docs/intercom-integration.md)**IncludesParser**API response optimization utility[Guide](docs/includes-parser.md)### Quick Examples

[](#quick-examples)

#### Enable Request Lifecycle Logging

[](#enable-request-lifecycle-logging)

```
// 1. Extend RequestLoggingMiddleware
class ServiceRequestLogger extends RequestLoggingMiddleware {
    protected function getServiceName(): string {
        return 'auth-service';
    }

    protected function addServiceContext($request, $context) {
        // Add route-specific context (JWT user context is automatically added)
        if ($userId = $request->route('userId')) {
            $context['target_user_id'] = $userId; // Route parameter, not JWT user
        }
        return $context;
    }

    // 3. Payload logging is disabled by default for security
    // Enable only when needed for debugging/development

    // 4. Optional: Configure path exclusions and payload logging
    public function __construct() {
        $this->configure([
            'excluded_paths' => ['/health*', '/metrics'], // Supports exact matches, globs, and prefixes
            'request_id_header' => 'X-Request-ID',
            // SECURITY: Payload logging disabled by default - only enable when needed
            'log_request_payload' => true, // Enable for debugging/development only
            // Both enabled by default - only specify if you want to disable:
            // 'add_request_id_to_response' => false,
            // 'add_trace_id_to_response' => false,
        ]);
        // Note: middleware-level exclusions complement any global defaults
    }
}

// 2. Register in Kernel.php
protected $middleware = [
    \App\Http\Middleware\ServiceRequestLogger::class,
];

// 4. Service calls automatically propagate traces
$this->productRepository->findByIds($productIds);
// Headers automatically include X-Amzn-Trace-Id
```

#### Configure Logging

[](#configure-logging)

```
// 1. Create service-specific LogFields
class OrderLogFields extends LogFields {
    const ORDER_ID = 'order_id';
    const ORDER_STATUS = 'order_status';
}

// 2. Configure Monolog
use NuiMarkets\LaravelSharedUtils\Logging\CustomizeMonoLog as BaseCustomizeMonoLog;

class ServiceCustomizeMonoLog extends BaseCustomizeMonoLog {
    protected function createTargetProcessor() {
        return new AddTargetProcessor('order-service');
    }
}

// 3. Configure sensitive data redaction
// Option 1: Default behavior (auth + PII fields redacted)
$processor = new SensitiveDataProcessor();

// Option 2: Preserve debugging fields while still redacting PII
$processor = new SensitiveDataProcessor(['user_email', 'ip_address']);

// Option 3: Fluent configuration
$processor = (new SensitiveDataProcessor())
    ->preserveFields(['user_email', 'ip_address']); // Keep email and IP for debugging

// Option 4: Disable PII redaction (only auth fields)
$processor = new SensitiveDataProcessor([], false);

// 4. Logs automatically route to correct Elasticsearch index
Log::info('Order processed', ['order_id' => $order->id]);
```

#### Standardize JSON API Validation

[](#standardize-json-api-validation)

```
// 1. Use trait in FormRequest classes
use NuiMarkets\LaravelSharedUtils\Http\Requests\JsonApiValidation;

class CreateOrderRequest extends FormRequest {
    use JsonApiValidation;

    public function rules() {
        return ['email' => 'required|email'];
    }
}

// 2. Consistent error format across all services (uses Laravel dot-notation in pointers)
{
    "meta": {"message": "Validation Failed", "status": 422},
    "errors": [{
        "status": "422",
        "title": "Validation Error",
        "detail": "The email field is required.",
        "source": {"pointer": "/data/attributes/email"}
    }]
}
```

#### Add Health Checks

[](#add-health-checks)

```
// Routes automatically available at /healthcheck
Route::get('/healthcheck', [HealthCheckController::class, 'detailed']);

// Response includes all infrastructure status
{
    "status": "healthy",
    "checks": {
        "database": {"status": "up", "response_time": "5ms"},
        "cache": {"status": "up", "driver": "redis"},
        "queue": {"status": "up", "jobs_pending": 0}
    }
}
```

Advanced Configuration
----------------------

[](#advanced-configuration)

### Configurable Path Exclusions

[](#configurable-path-exclusions)

Customize which paths to exclude from request logging:

```
class ServiceRequestLogger extends RequestLoggingMiddleware {
    public function __construct() {
        $this->configure([
            'excluded_paths' => ['/healthcheck', '/health', '/metrics', '/status'],
            'request_id_header' => 'X-Request-ID',
            // Response headers enabled by default - only specify to disable:
            // 'add_request_id_to_response' => false,
            // 'add_trace_id_to_response' => false,
        ]);
    }
}
```

### Flexible Sensitive Data Redaction

[](#flexible-sensitive-data-redaction)

Balance privacy compliance with debugging needs:

```
// Default: PII redaction enabled by default
$processor = new SensitiveDataProcessor();

// Debugging-friendly: Preserve email and IP for troubleshooting
$processor = new SensitiveDataProcessor(['user_email', 'ip_address']);

// Fluent configuration
$processor = (new SensitiveDataProcessor())
    ->preserveFields(['user_email', 'ip_address']);

// Note: Some organizations treat user-agent as PII
// To preserve user-agent for debugging while redacting other PII:
$processor = new SensitiveDataProcessor(['user_agent']);

// Disable PII redaction (only auth fields)
$processor = new SensitiveDataProcessor([], false);
```

**Field Categories:**

- **Auth fields** (always redacted): password, token, secret, api\_key, jwt, bearer
- **PII fields** (redacted by default): email, phone, address, ssn, credit\_card, bank\_account
- **Preserve fields**: Override redaction for specific debugging-friendly fields

Architecture
------------

[](#architecture)

This package follows a **trait-based architecture** allowing you to:

- Use only the components you need
- Extend base classes for customization
- Integrate gradually into existing codebases

### No Service Provider Required

[](#no-service-provider-required)

The package intentionally doesn't auto-register a service provider, giving you full control over which components to use.

### Cross-Version Compatibility

[](#cross-version-compatibility)

LaravelPHPMonologOrchestra Testbench8.x8.0+2.x7.x9.x8.0+2.x7.x10.x8.1+3.x8.xConfiguration
-------------

[](#configuration)

### Environment Variables

[](#environment-variables)

```
# Distributed Tracing (automatic with X-Ray)
# No configuration needed!

# Logging
LOG_TARGET=my-service
APP_DEBUG=true

# RemoteRepository
API_GATEWAY_ENDPOINT=https://api.example.com
REMOTE_REPOSITORY_MAX_URL_LENGTH=2048
REMOTE_REPOSITORY_LOG_REQUESTS=true

# Intercom
INTERCOM_ENABLED=true
INTERCOM_TOKEN=your_token
INTERCOM_SERVICE_NAME=my-service
```

### RemoteRepository Configuration

[](#remoterepository-configuration)

Add to your `config/app.php`:

```
'remote_repository' => [
    'base_uri' => env('API_GATEWAY_ENDPOINT'),
    'max_url_length' => env('REMOTE_REPOSITORY_MAX_URL_LENGTH', 2048),
    'log_requests' => env('REMOTE_REPOSITORY_LOG_REQUESTS', true),

    // Failure caching (optional - defaults shown)
    'failure_cache_ttl' => env('REMOTE_FAILURE_CACHE_TTL', 120),
    'failure_cache_ttl_by_category' => [
        'not_found' => 600,      // 10 min for 404s
        'timeout' => 30,         // 30 sec for timeouts
        'server_error' => 120,   // 2 min for 5xx errors
    ],
],
```

[See full migration guide →](docs/RemoteRepository.md#migration-guide)

Testing
-------

[](#testing)

```
# Run all tests
composer test-all

# Run specific tests
composer test RequestMetrics

# Generate coverage report
composer test-coverage

# Code quality
composer lint    # Check code style
composer format  # Fix code style
```

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

[](#contributing)

We welcome contributions! Please follow these guidelines:

1. Fork the repository and create your branch from `master`
2. Add tests for any new functionality
3. Ensure the test suite passes (`composer test-all`)
4. Follow the existing code style (`composer lint` and `composer format`)
5. Update documentation as needed
6. Submit a pull request with a clear description of changes

Performance Impact
------------------

[](#performance-impact)

- **Distributed Tracing**: &lt; 1ms overhead per request
- **Logging**: Asynchronous processing, no request blocking
- **Health Checks**: Cached results available, configurable timeouts
- **RemoteRepository**: Built-in caching reduces API calls by up to 80%

Security
--------

[](#security)

- Automatic redaction of sensitive data in logs
- JWT token validation for service-to-service communication
- Environment-aware security settings
- No credentials stored in code

License
-------

[](#license)

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

Support
-------

[](#support)

- [Documentation](docs/)
- [Issue Tracker](https://github.com/nuimarkets/nui-laravel-shared-utils/issues)
- [Discussions](https://github.com/nuimarkets/nui-laravel-shared-utils/discussions)

---

Built with ❤️ by [Nui Markets](https://nuimarkets.com)

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance89

Actively maintained with recent releases

Popularity24

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.4% 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

Every ~6 days

Total

70

Last Release

56d ago

### Community

Maintainers

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

---

Top Contributors

[![hampsterx](https://avatars.githubusercontent.com/u/1887721?v=4)](https://github.com/hampsterx "hampsterx (195 commits)")[![griessel-jc](https://avatars.githubusercontent.com/u/65710615?v=4)](https://github.com/griessel-jc "griessel-jc (14 commits)")[![stevenoffspring](https://avatars.githubusercontent.com/u/169628034?v=4)](https://github.com/stevenoffspring "stevenoffspring (2 commits)")

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/nuimarkets-laravel-shared-utils/health.svg)

```
[![Health](https://phpackages.com/badges/nuimarkets-laravel-shared-utils/health.svg)](https://phpackages.com/packages/nuimarkets-laravel-shared-utils)
```

###  Alternatives

[google/cloud-core

Google Cloud PHP shared dependency, providing functionality useful to all components.

343121.4M79](/packages/google-cloud-core)[gehrisandro/tailwind-merge-laravel

TailwindMerge for Laravel merges multiple Tailwind CSS classes by automatically resolving conflicts between them

341682.2k18](/packages/gehrisandro-tailwind-merge-laravel)[backpack/basset

Dead-simple way to load CSS or JS assets only once per page, when using Laravel 10+.

202832.4k6](/packages/backpack-basset)[firefly-iii/data-importer

Firefly III Data Import Tool.

7545.8k](/packages/firefly-iii-data-importer)[blair2004/nexopos

The Free Modern Point Of Sale System build with Laravel, TailwindCSS and Vue.js.

1.2k2.3k](/packages/blair2004-nexopos)[nickurt/laravel-akismet

Akismet for Laravel 11.x/12.x/13.x

97139.6k2](/packages/nickurt-laravel-akismet)

PHPackages © 2026

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