peal-ihertz/laravel-nats

Laravel integration for basis-company/nats (NATS JetStream client)

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/peal-ihertz/laravel-nats

dev-main 2025-10-18 12:29 UTC

This package is auto-updated.

Last update: 2025-10-18 12:29:18 UTC


README

Effortless real-time communication for Laravel apps using NATS.io via basis-company/nats.php

๐Ÿงฉ Overview

Laravel NATS is a wrapper package that allows Laravel developers to interact easily with the NATS messaging system.

NATS (Neural Autonomic Transport System) is a high-performance, lightweight messaging system for microservices, IoT, and distributed systems.

With this package, you can:

  • ๐Ÿ“ค Publish messages to NATS subjects
  • ๐Ÿ“ฉ Subscribe to messages
  • ๐Ÿ” Request/Reply pattern using callbacks
  • โš™๏ธ Integrate seamlessly within controllers, commands, or queued jobs
  • ๐Ÿง  Use Laravel Facades, Service Container bindings, and Configuration
  • ๐Ÿงช Test easily using PestPHP

โš™๏ธ Installation

composer require peal-ihertz/laravel-nats dev-main

๐Ÿงฐ Configuration

Publish the config file (optional):

php artisan vendor:publish --tag=config

This will create:

// config/nats.php

return [
    'host' => env('NATS_HOST', '127.0.0.1'),
    'port' => env('NATS_PORT', 4222),
];

You can connect your Dockerized NATS instance or remote cluster:

NATS_HOST=nats
NATS_PORT=4222

๐Ÿงฑ Usage

๐Ÿ”น Publish a Message

use Nats;

Nats::publish('notifications.new', ['message' => 'New user registered']);

or manually with a payload:

use Basis\Nats\Message\Payload;

$payload = new Payload(json_encode(['id' => 123]));
Nats::publish('orders.created', $payload);

๐Ÿ”น Subscribe to a Subject

use Nats;

Nats::subscribe('notifications.new', function ($msg) {
    $data = json_decode($msg->body, true);
    logger('New notification received:', $data);
});

๐Ÿ”น Request/Reply (Callback Pattern)

NATS supports RPC-style communication through a request-reply mechanism.

Client Side:

Nats::request('math.add', ['a' => 5, 'b' => 3], function ($response) {
    $data = json_decode($response->body, true);
    logger('Response from server:', $data);
});

Server Side (Subscriber):

Nats::subscribe('math.add', function ($msg) {
    $data = json_decode($msg->body, true);
    $sum = $data['a'] + $data['b'];

    $msg->reply(json_encode(['sum' => $sum]));
});

โœ… The callback executes once the reply arrives โ€” making it ideal for interactive real-time systems.

๐Ÿ”น Example Controller

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Nats;

class NatsController extends Controller
{
    public function send()
    {
        Nats::publish('notifications.new', ['event' => 'UserRegistered']);
        return response()->json(['message' => 'Notification sent!']);
    }

    public function request()
    {
        Nats::request('math.add', ['a' => 10, 'b' => 7], function ($response) {
            logger('Received reply:', [json_decode($response->body, true)]);
        });

        return response()->json(['status' => 'request sent']);
    }
}

๐Ÿง  Advanced Features

1. JetStream Support (Optional)

If you use NATS JetStream, you can extend this package to handle durable streams and message persistence.
The underlying client supports JetStream commands and metadata.

2. Durable Subscriptions

Persistent subscriptions let you replay missed messages and process them at-least-once.

3. Async Handling

NATS supports fully asynchronous publish/subscribe and request/reply patterns.

4. Clustered & Secure

You can connect to multiple NATS servers, use TLS, and authentication via NATS tokens.

๐Ÿงช Testing

Running Tests

This package uses PestPHP.

Run all tests:

./vendor/bin/pest

Feature tests example (tests/Feature/NatsPublishTest.php):

it('can publish messages to nats', function () {
    $client = Mockery::mock(\Basis\Nats\Client::class);
    $client->shouldReceive('publish')->once();
    app()->instance(\Basis\Nats\Client::class, $client);

    Nats::publish('test.subject', ['foo' => 'bar']);
});

๐Ÿณ Example Docker Compose (for NATS testing)

version: "3"
services:
  nats:
    image: nats:latest
    ports:
      - "4222:4222"
      - "8222:8222"

Run:

docker-compose up -d

๐Ÿ’ก Why Use NATS with Laravel?

Feature Description
โšก Speed Handles millions of messages per second
๐Ÿงฉ Simplicity Easy subject-based routing
๐Ÿ” Request/Reply Built-in microservice communication
โ˜๏ธ Scalable Cluster and stream messages easily
๐Ÿง  Lightweight Zero dependencies for core message broker
๐Ÿ” Secure TLS and user authentication supported

๐Ÿงพ License

MIT License ยฉ 2025 Mohammed Minuddin Peal - iHERTZ Technology