PHPackages                             opennebel/laravel-kafka - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. opennebel/laravel-kafka

ActiveLibrary[HTTP &amp; Networking](/categories/http)

opennebel/laravel-kafka
=======================

A Laravel wrapper around php-rdkafka to produce Kafka messages easily.

v1.0.5(11mo ago)4349[1 issues](https://github.com/OpenNebel/LaravelKafka/issues)MITPHPPHP ^8.0

Since Jul 1Pushed 11mo agoCompare

[ Source](https://github.com/OpenNebel/LaravelKafka)[ Packagist](https://packagist.org/packages/opennebel/laravel-kafka)[ GitHub Sponsors](https://github.com/sponsors/OpenNebel)[ RSS](/packages/opennebel-laravel-kafka/feed)WikiDiscussions master Synced today

READMEChangelog (4)Dependencies (4)Versions (8)Used By (0)

LaravelKafka
============

[](#laravelkafka)

**LaravelKafka** is a simple yet powerful library for producing messages to Apache Kafka from your Laravel applications. It builds upon [php-rdkafka](https://github.com/arnaud-lb/php-rdkafka) and adheres to Laravel conventions, including Service Providers, Facades, Queueable Jobs, Artisan commands, dependency injection, and configuration.

> 🔧 Maintained by [OpenNebel](https://github.com/opennebel)

---

🧩 Features
----------

[](#-features)

- ✅ **Synchronous** Kafka message sending
- 🔁 **Asynchronous** support via Laravel's queue system
- 🧱 Modular structure (producers, config, jobs, DLQ)
- 🧠 Support for headers, keys, partitions, msgflags
- 🛠 Error handling (Dead Letter Queue with full Kafka options)
- 🧪 Integrated Artisan commands (`status`, `retry-failed`)
- 📦 Compatible with Laravel Horizon, Telescope, Docker, CI/CD

---

🚀 Installation
--------------

[](#-installation)

### 1. Install the PHP Kafka extension

[](#1-install-the-php-kafka-extension)

```
pecl install rdkafka
```

> 📌 Ensure `php.ini` loads the extension: `extension=rdkafka`

### 2. Install the library

[](#2-install-the-library)

```
composer require opennebel/laravel-kafka
```

---

⚙️ Configuration
----------------

[](#️-configuration)

### Method 1 – Full Publication (config + migration)

[](#method-1--full-publication-config--migration)

```
php artisan vendor:publish --tag=laravel-kafka
```

### Method 2 – Separate Publication

[](#method-2--separate-publication)

```
# Only the config
php artisan vendor:publish --tag=laravel-kafka-config

# Only the DLQ migration
php artisan vendor:publish --tag=laravel-kafka-migrations
```

### `.env` File

[](#env-file)

```
KAFKA_BROKERS=localhost:9092
KAFKA_DEFAULT_TOPIC=notification-events

# For asynchronous sending via Laravel Queue
KAFKA_ASYNC_ENABLED=true
KAFKA_ASYNC_QUEUE=default
```

---

✉️ Sending Messages
-------------------

[](#️-sending-messages)

### 🔹 Synchronous Sending

[](#-synchronous-sending)

```
use OpenNebel\LaravelKafka\Facades\Kafka;

// Raw message with options
Kafka::produce('notification-events', 'Hello Kafka', [
    'key' => 'user:123',
    'headers' => ['x-app' => 'mondialgp'],
    'partition' => 0,
    'flag' => 0
]);

// JSON message
Kafka::produceJson('notification-events', [
    'type' => 'email',
    'to' => 'user@example.com',
    'subject' => 'Welcome',
    'variables' => ['name' => 'John']
]);
```

### 🔸 Asynchronous Sending (Laravel Queue)

[](#-asynchronous-sending-laravel-queue)

```
Kafka::produceAsync('notification-events', [
    'type' => 'sms',
    'to' => '+33600000000',
    'message' => 'Your code is 1234'
], [
    'key' => 'job:456',
    'headers' => ['x-job' => 'welcome']
]);

Kafka::produceAsyncToDefault([
    'type' => 'sms',
    'to' => '+33600000000',
    'message' => 'Your code is 1234'
], [
    'key' => 'default-key'
]);
```

> Start the worker to process jobs:

```
php artisan queue:work
```

---

🧩 Usage with Dependency Injection
---------------------------------

[](#-usage-with-dependency-injection)

```
use OpenNebel\LaravelKafka\KafkaService;

public function handle(KafkaService $kafka)
{
    $kafka->produceToDefault('message via DI', [
        'headers' => ['x-di' => 'used']
    ]);
}
```

---

💥 Error Handling (DLQ)
----------------------

[](#-error-handling-dlq)

If `flush()` fails or the broker is unreachable, the message is:

- recorded in the `kafka_failed_messages` table
- all Kafka `options` are stored as JSON
- accessible via Artisan command
- manually re-attemptable

### Migration:

[](#migration)

```
php artisan migrate
```

### Retry Failed Messages:

[](#retry-failed-messages)

```
php artisan kafka:retry-failed
```

---

🛠 Artisan Commands
------------------

[](#-artisan-commands)

CommandDescription`kafka:status`Checks Kafka broker connectivity and lists metadata`kafka:retry-failed`Retries messages in the DLQThese commands are **auto-registered** via `KafkaServiceProvider`.

---

🧰 Service API
-------------

[](#-service-api)

MethodDescription`produce()`Raw string to topic with optional headers/key/partition/msgflags`produceJson()`JSON payload to topic`produceToDefault()`Raw string to default topic`produceJsonToDefault()`JSON payload to default topic`produceAsync()`Dispatch async job to a topic`produceAsyncToDefault()`Dispatch async job to default topic`flush($timeoutMs)`Flush local queue to Kafka broker`getQueueLength()`Messages in local Kafka buffer`ping()`Kafka connection test`getMetadata()`Cluster info: topics, partitions, brokers`isConnected()`Indicates producer was created correctly---

📂 Configuration (`config/kafka.php`)
------------------------------------

[](#-configuration-configkafkaphp)

```
return [
    'brokers' => env('KAFKA_BROKERS', 'localhost:9092'),
    'default_topic' => env('KAFKA_DEFAULT_TOPIC', 'notification-events'),

    'async' => [
        'enabled' => env('KAFKA_ASYNC_ENABLED', true),
        'queue' => env('KAFKA_ASYNC_QUEUE', 'default'),
    ],

    'options' => [
        // Kafka global options (passed to php-rdkafka Producer config)
        // e.g. 'compression.codec' => 'snappy'
    ],
];
```

---

✅ Prerequisites
---------------

[](#-prerequisites)

- PHP &gt;= 8.0
- Laravel &gt;= 9.x
- `ext-rdkafka` PHP extension
- Kafka broker (local, Docker, or cloud)

---

🧠 Recommendations
-----------------

[](#-recommendations)

- Use Laravel Horizon to manage async jobs
- Monitor failures with Telescope or Sentry
- Track Kafka logs via `storage/logs/laravel.log`

---

📄 License
---------

[](#-license)

MIT © [OpenNebel](https://github.com/opennebel)

###  Health Score

31

—

LowBetter than 66% of packages

Maintenance45

Moderate activity, may be stable

Popularity15

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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

Every ~6 days

Total

6

Last Release

338d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7af801bf2a35232f87ae59dce662c04ba46a13a2816e0d0e048352fe855cd8b5?d=identicon)[OpenNebel](/maintainers/OpenNebel)

---

Top Contributors

[![Duorly](https://avatars.githubusercontent.com/u/52921005?v=4)](https://github.com/Duorly "Duorly (9 commits)")

---

Tags

laravelkafkaproducerphp-rdkafkaevent-streamingopennebel

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/opennebel-laravel-kafka/health.svg)

```
[![Health](https://phpackages.com/badges/opennebel-laravel-kafka/health.svg)](https://phpackages.com/packages/opennebel-laravel-kafka)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58171.4k14](/packages/api-platform-laravel)[leroy-merlin-br/metamorphosis

Kafka package for laravel applications

4230.2k](/packages/leroy-merlin-br-metamorphosis)[onlime/laravel-http-client-global-logger

A global logger for the Laravel HTTP Client

2038.9k](/packages/onlime-laravel-http-client-global-logger)

PHPackages © 2026

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