PHPackages                             salmanzafar/laravel-mqtt - 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. salmanzafar/laravel-mqtt

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

salmanzafar/laravel-mqtt
========================

A simple Laravel Library to connect/publish/subscribe to MQTT broker

v3.0.0(2w ago)102158.3k↓53.8%341MITPHPPHP ^7.2 || ^8.0CI passing

Since Jun 11Pushed 2w ago2 watchersCompare

[ Source](https://github.com/salmanzafar949/MQTT-Laravel)[ Packagist](https://packagist.org/packages/salmanzafar/laravel-mqtt)[ Fund](https://paypal.me/salmanzafar949)[ RSS](/packages/salmanzafar-laravel-mqtt/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (2)Dependencies (3)Versions (23)Used By (1)

Laravel MQTT
============

[](#laravel-mqtt)

[![Latest Version on Packagist](https://camo.githubusercontent.com/ab6ca6927fa7b9f568adc5c1feeb9c9630747bd92ac103b26af5c13f4133e478/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616c6d616e7a616661722f6c61726176656c2d6d7174742e737667)](https://packagist.org/packages/salmanzafar/laravel-mqtt)[![Total Downloads](https://camo.githubusercontent.com/ee5ede0495d749c859044776f15739bd97ed21656c5be7325a5e975e17a417f3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73616c6d616e7a616661722f6c61726176656c2d6d7174742e737667)](https://packagist.org/packages/salmanzafar/laravel-mqtt)[![Tests](https://github.com/salmanzafar949/MQTT-Laravel/actions/workflows/tests.yml/badge.svg)](https://github.com/salmanzafar949/MQTT-Laravel/actions/workflows/tests.yml)[![License](https://camo.githubusercontent.com/e32148cff34fbb775f4ec04e1d8ab502b80ae1574a10eb067ba81b347640b7ec/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73616c6d616e7a616661722f6c61726176656c2d6d7174742e737667)](LICENSE)

A simple Laravel library to connect, publish and subscribe to an MQTT broker.

Based on [bluerhinos/phpMQTT](https://github.com/bluerhinos/phpMQTT). A working example application is available in the [Laravel-Mqtt-Example](https://github.com/salmanzafar949/Laravel-Mqtt-Example) repo.

Table of contents
-----------------

[](#table-of-contents)

- [Compatibility](#compatibility)
- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
    - [Publishing](#publishing)
    - [Subscribing](#subscribing)
    - [Multiple topics](#subscribing-to-multiple-topics)
    - [Helper functions](#helper-functions)
- [TLS / SSL](#tls--ssl)
- [Error handling](#error-handling)
- [Available methods](#available-methods)
- [Testing &amp; quality](#testing--quality)
- [Releasing](#releasing)
- [Changelog](#changelog)
- [Contributing](#contributing)
- [License](#license)

Compatibility
-------------

[](#compatibility)

PHPLaravel7.2 – 8.45.5 – 12.xThe package uses Laravel's package auto-discovery, so it works out of the box across all of the above versions.

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

[](#installation)

```
composer require salmanzafar/laravel-mqtt
```

The service provider and `Mqtt` facade are registered automatically on Laravel 5.5+. **Only** if you are on Laravel &lt; 5.5, register them manually in `config/app.php`:

```
'providers' => [
    Salman\Mqtt\MqttServiceProvider::class,
],

'aliases' => [
    'Mqtt' => Salman\Mqtt\Facades\Mqtt::class,
],
```

Configuration
-------------

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="Salman\Mqtt\MqttServiceProvider"
```

This creates `config/mqtt.php`:

```
return [
    'host'       => env('MQTT_HOST', '127.0.0.1'),
    'password'   => env('MQTT_PASSWORD', ''),
    'username'   => env('MQTT_USERNAME', ''),
    'port'       => env('MQTT_PORT', '1883'),
    'timeout'    => (int) env('MQTT_TIMEOUT', 10),
    'keepalive'  => (int) env('MQTT_KEEPALIVE', 10),
    'debug'      => (bool) env('MQTT_DEBUG', false),
    'qos'        => env('MQTT_QOS', 0),
    'retain'     => env('MQTT_RETAIN', 0),
    'exceptions' => (bool) env('MQTT_EXCEPTIONS', false),

    // TLS / SSL
    'certfile'   => env('MQTT_CERT_FILE', ''),
    'localcert'  => env('MQTT_LOCAL_CERT', ''),
    'localpk'    => env('MQTT_LOCAL_PK', ''),
    'tls' => [
        'verify_peer'       => (bool) env('MQTT_TLS_VERIFY_PEER', true),
        'verify_peer_name'  => (bool) env('MQTT_TLS_VERIFY_PEER_NAME', true),
        'allow_self_signed' => (bool) env('MQTT_TLS_ALLOW_SELF_SIGNED', false),
        'ciphers'           => env('MQTT_TLS_CIPHERS', null),
        'passphrase'        => env('MQTT_TLS_PASSPHRASE', null),
    ],
];
```

KeyEnv varDefaultDescription`host``MQTT_HOST``127.0.0.1`Broker host.`port``MQTT_PORT``1883`Broker port (`8883` for TLS).`username``MQTT_USERNAME``''`Username, if the broker requires authentication.`password``MQTT_PASSWORD``''`Password, if the broker requires authentication.`timeout``MQTT_TIMEOUT``10`Connection timeout in seconds.`keepalive``MQTT_KEEPALIVE``10`Seconds between keep-alive pings.`debug``MQTT_DEBUG``false`Enable debug logging.`qos``MQTT_QOS``0`Quality of Service level.`retain``MQTT_RETAIN``0`Retain flag (`0` or `1`).`exceptions``MQTT_EXCEPTIONS``false`Throw on failure instead of returning `false`.`tls``MQTT_TLS_*`see aboveSSL stream-context options used when a CA file is set.When running inside Laravel, debug and error messages are written through the framework logger.

Usage
-----

[](#usage)

### Publishing

[](#publishing)

Using the class directly:

```
use Salman\Mqtt\MqttClass\Mqtt;

public function sendMessage(string $topic, string $message)
{
    $mqtt      = new Mqtt();
    $clientId  = optional(auth()->user())->id;

    $published = $mqtt->ConnectAndPublish($topic, $message, $clientId);

    return $published ? 'published' : 'failed';
}
```

Using the facade:

```
use Mqtt; // or: use Salman\Mqtt\Facades\Mqtt;

$published = Mqtt::ConnectAndPublish($topic, $message, $clientId);
```

> `$client_id` and `$retain` are optional: `ConnectAndPublish($topic, $message)`works too. When no client id is given, a unique one is generated for you.

### Subscribing

[](#subscribing)

```
use Salman\Mqtt\MqttClass\Mqtt;

public function subscribe(string $topic)
{
    $mqtt = new Mqtt();

    $mqtt->ConnectAndSubscribe($topic, function ($topic, $message) {
        echo "Message received on {$topic}: {$message}\n";
    });
}
```

Or via the facade:

```
Mqtt::ConnectAndSubscribe($topic, function ($topic, $message) {
    logger()->info("MQTT message on {$topic}", ['message' => $message]);
});
```

> Subscribing blocks the process while it listens, so run it from an Artisan command / queue worker rather than an HTTP request.

### Subscribing to multiple topics

[](#subscribing-to-multiple-topics)

Pass an array of topics to listen to several at once:

```
Mqtt::ConnectAndSubscribe(['sensors/temperature', 'sensors/humidity'], function ($topic, $message) {
    echo "{$topic} => {$message}\n";
});
```

### Helper functions

[](#helper-functions)

Two convenience helpers are also available:

```
// Publish
connectToPublish($topic, $message, $clientId = null, $retain = null);

// Subscribe (echoes received messages)
connectToSubscribe($topic, $clientId = null);
```

TLS / SSL
---------

[](#tls--ssl)

Provide a CA file (and optionally a client certificate) to connect over `tls://`. Set the broker port to `8883` and configure the certificate paths:

```
MQTT_PORT=8883
MQTT_CERT_FILE=/path/to/ca.crt
MQTT_LOCAL_CERT=/path/to/client.crt
MQTT_LOCAL_PK=/path/to/client.key
```

Fine-tune verification through the `mqtt.tls` options (for example set `MQTT_TLS_ALLOW_SELF_SIGNED=true` for a self-signed broker in development). Keep the `verify_peer` options enabled in production.

Error handling
--------------

[](#error-handling)

By default the connection methods return `false` on failure. If you prefer exceptions, enable them:

```
MQTT_EXCEPTIONS=true
```

```
use Salman\Mqtt\Exceptions\MqttConnectionException;

try {
    Mqtt::ConnectAndPublish($topic, $message);
} catch (MqttConnectionException $e) {
    report($e);
}
```

Available methods
-----------------

[](#available-methods)

MethodReturnsDescription`ConnectAndPublish(string $topic, string $message, string|int $clientId = null, int $retain = null)``bool`Connect, publish a message and disconnect.`ConnectAndSubscribe(string|array $topic, callable $callback, string|int $clientId = null)``bool`Connect and listen for messages on one or more topics.> PHP method names are case-insensitive, so `Mqtt::connectAndPublish(...)` and `Mqtt::connectAndSubscribe(...)` work as well.

Testing &amp; quality
---------------------

[](#testing--quality)

```
composer install
composer test        # PHPUnit
```

Code style (Laravel Pint) and static analysis (PHPStan) are also available:

```
composer lint        # check code style
composer lint:fix    # apply code-style fixes
composer analyse     # run PHPStan
```

The Pint and PHPStan binaries are installed on demand by the `quality` CI workflow; to run them locally add them once with `composer require --dev laravel/pint larastan/larastan`.

Releasing
---------

[](#releasing)

Releases are published to [Packagist](https://packagist.org/packages/salmanzafar/laravel-mqtt)automatically. Packagist is connected to this repository via the Packagist GitHub App, and a GitHub Actions workflow tags releases from the `version`field in `composer.json`:

1. Bump `"version"` in `composer.json` (and update `CHANGELOG.md`) in your pull request.
2. Merge the pull request into `master`.
3. The `release` workflow runs the test suite, creates the matching `vX.Y.Z`tag and GitHub Release, and Packagist publishes the new version.

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for a list of changes.

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

[](#contributing)

Contributions are welcome — please read [CONTRIBUTING.md](CONTRIBUTING.md) first.

License
-------

[](#license)

The MIT License (MIT). See [LICENSE](LICENSE) for details.

###  Health Score

65

—

FairBetter than 99% of packages

Maintenance96

Actively maintained with recent releases

Popularity49

Moderate usage in the ecosystem

Community22

Small or concentrated contributor base

Maturity75

Established project with proven stability

 Bus Factor1

Top contributor holds 69.7% 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 ~137 days

Recently: every ~513 days

Total

20

Last Release

20d ago

Major Versions

v1.0.9 → v2.0.02020-09-20

v2.0.8 → v3.0.02026-07-30

PHP version history (7 changes)v1.0.0PHP &gt;=5.4.0

v1.0.4PHP &gt;=7.4.0

v1.0.5PHP &gt;=7

v1.0.6PHP &gt;=7.3

v2.0.3PHP ^7.0 || ^7.1 || ^7.2 || ^7.3 || ^7.4

v2.0.4PHP ^7.0 || ^7.1 || ^7.2 || ^7.3 || ^7.4 || ^8.0

v3.0.0PHP ^7.2 || ^8.0

### Community

Maintainers

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

---

Top Contributors

[![salmanzafar40](https://avatars.githubusercontent.com/u/29972877?v=4)](https://github.com/salmanzafar40 "salmanzafar40 (69 commits)")[![salmanzafar949](https://avatars.githubusercontent.com/u/29015432?v=4)](https://github.com/salmanzafar949 "salmanzafar949 (19 commits)")[![claude](https://avatars.githubusercontent.com/u/81847?v=4)](https://github.com/claude "claude (8 commits)")[![Casdak7](https://avatars.githubusercontent.com/u/33229620?v=4)](https://github.com/Casdak7 "Casdak7 (1 commits)")[![TMogdans](https://avatars.githubusercontent.com/u/19358139?v=4)](https://github.com/TMogdans "TMogdans (1 commits)")[![wilianx7](https://avatars.githubusercontent.com/u/42422976?v=4)](https://github.com/wilianx7 "wilianx7 (1 commits)")

---

Tags

iotlaravellaravel-packagemqttmqtt-clientphppubsubphplaravellaravel 6laravel 7laravel 8laravel 9laravel 10laravel 11laravel 12laravel 5laravel5php-8laravel12laravel11laravel6laravel8laravel9laravel7laravel10php 8.1php 8.2php 8.3php 8.4php-7.4mqtt-laravelmqtt-laravel-publishermqtt-laravel-subscriberlaravel mqtt librarylaravel-mqtt

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/salmanzafar-laravel-mqtt/health.svg)

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

###  Alternatives

[onecentlin/laravel-adminer

Laravel Adminer Database Manager

261548.5k3](/packages/onecentlin-laravel-adminer)[ip2location/ip2location-laravel

Lookup for visitor's IP information, such as country, region, city, coordinates, zip code, time zone, ISP, domain name, connection type, area code, weather, MCC, MNC, mobile brand name, elevation and usage type.

83562.9k1](/packages/ip2location-ip2location-laravel)[tuncaybahadir/quar

A simple QR Code generation tool for your projects with Laravel 10, 11, 12, 13 versions, php 8.2, 8.3, 8.4 and 8.5

82133.8k6](/packages/tuncaybahadir-quar)[itsmurumba/laravel-mpesa

Laravel Package for Mpesa Daraja API

2011.1k](/packages/itsmurumba-laravel-mpesa)

PHPackages © 2026

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