PHPackages                             peal-ihertz/laravel-nats - 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. peal-ihertz/laravel-nats

ActiveLibrary

peal-ihertz/laravel-nats
========================

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

02PHP

Since Oct 18Pushed 6mo agoCompare

[ Source](https://github.com/moin786/laravel-nats)[ Packagist](https://packagist.org/packages/peal-ihertz/laravel-nats)[ RSS](/packages/peal-ihertz-laravel-nats/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

🚀 Laravel NATS Integration Package
==================================

[](#-laravel-nats-integration-package)

### Effortless real-time communication for Laravel apps using [NATS.io](https://nats.io) via [basis-company/nats.php](https://github.com/basis-company/nats.php)

[](#effortless-real-time-communication-for-laravel-apps-using-natsio-via-basis-companynatsphp)

---

🧩 Overview
----------

[](#-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
---------------

[](#️-installation)

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

---

🧰 Configuration
---------------

[](#-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
-------

[](#-usage)

### 🔹 Publish a Message

[](#-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

[](#-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)

[](#-requestreply-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

[](#-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
-------------------

[](#-advanced-features)

### 1. **JetStream Support (Optional)**

[](#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**

[](#2-durable-subscriptions)

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

### 3. **Async Handling**

[](#3-async-handling)

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

### 4. **Clustered &amp; Secure**

[](#4-clustered--secure)

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

---

🧪 Testing
---------

[](#-testing)

### Running Tests

[](#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)
-------------------------------------------

[](#-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?
----------------------------

[](#-why-use-nats-with-laravel)

FeatureDescription⚡ SpeedHandles millions of messages per second🧩 SimplicityEasy subject-based routing🔁 Request/ReplyBuilt-in microservice communication☁️ ScalableCluster and stream messages easily🧠 LightweightZero dependencies for core message broker🔐 SecureTLS and user authentication supported---

🧾 License
---------

[](#-license)

MIT License © 2025 [Mohammed Minuddin Peal - iHERTZ Technology](https://ihertztech.com)

###  Health Score

17

—

LowBetter than 6% of packages

Maintenance46

Moderate activity, may be stable

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/171ff00d2636607267851b5600ddb93bdeb77b62dca6f1b6c031dd6f40a3753d?d=identicon)[moin786](/maintainers/moin786)

---

Top Contributors

[![moin786](https://avatars.githubusercontent.com/u/12525167?v=4)](https://github.com/moin786 "moin786 (6 commits)")

### Embed Badge

![Health badge](/badges/peal-ihertz-laravel-nats/health.svg)

```
[![Health](https://phpackages.com/badges/peal-ihertz-laravel-nats/health.svg)](https://phpackages.com/packages/peal-ihertz-laravel-nats)
```

PHPackages © 2026

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