1. Go to this page and download the library: Download hakhant/mqtt-client library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Hakhant\Broker\Client;
class MqttController extends Controller
{
protected $mqttClient;
public function __construct(Client $mqttClient)
{
$this->mqttClient = $mqttClient;
}
public function publishMessage()
{
$topic = 'topic/test';
$message = 'Hello from Laravel MQTT!';
$qos = 0; // Quality of Service level
$retain = false; // Whether the message should be retained
// Publish message
$this->mqttClient->publish($topic, $message, $qos, $retain);
return response()->json(['status' => 'Message Published']);
}
public function subscribeToTopic()
{
$topic = 'topic/test';
$this->mqttClient->subscribe($topic, function($topic, $message) {
// Handle the received message
echo "Message received on topic {$topic}: {$message}\n";
});
// Keep the loop running to listen for messages
$this->mqttClient->loop()
}
}