Laravel Broadcasting Vue Setup

User
Laravel broadcasting with example with external Vue application on same server
Assistant
### **Laravel Broadcasting with External Vue Application on the Same Server**
Laravel Broadcasting allows real-time event-driven communication between the backend and frontend using WebSockets. Below is a step-by-step guide to implementing broadcasting in Laravel with an external Vue application hosted on the same server.

## **1. Install Laravel Echo and Pusher (or Reverb for WebSockets)**
Since you are already using **Reverb** with port `6001`, we'll configure broadcasting using it.

### **Step 1: Install Laravel Echo and Pusher JS**
Run the following command inside your **Vue application**:

yarn add laravel-echo pusher-js

## **2. Configure Laravel for Broadcasting**
### **Step 2: Install Laravel Reverb**
Since you're using Laravel 10+ with PHP 8.3, Reverb is the best choice.

composer require laravel/reverb

### **Step 3: Publish Reverb Config**

php artisan vendor:publish --tag=reverb-config

Modify `.env` to enable broadcasting with Reverb:

BROADCAST_DRIVER=reverb
REVERB_HOST=127.0.0.1
REVERB_PORT=6001

Then start Reverb:

php artisan reverb:start

## **3. Create an Event for Broadcasting**
Generate a new event:

php artisan make:event MessageSent

Modify `app/Events/MessageSent.php`:

use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;

class MessageSent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return ['chat-channel'];
    }

    public function broadcastAs()
    {
        return 'message.sent';
    }
}

## **4. Trigger Event in Laravel**
In a controller (`ChatController`):

use AppEventsMessageSent;
use IlluminateHttpRequest;

class ChatController extends Controller
{
    public function sendMessage(Request $request)
    {
        $message = $request->input('message');

        broadcast(new MessageSent($message))->toOthers();

        return response()->json(['message' => 'Broadcasted successfully']);
    }
}

Define API Route (`routes/api.php`):

use AppHttpControllersChatController;

Route::post('/send-message', [ChatController::class, 'sendMessage']);

## **5. Configure Vue.js with Laravel Echo**
Inside your Vue application, create an `echo.js` file:

import Echo from "laravel-echo";
import Pusher from "pusher-js";

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: "pusher",
    key: "reverb",
    wsHost: "your-domain.com", // Replace with your server domain
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
    enabledTransports: ["ws", "wss"],
});

Then, listen for events in your Vue component:

<template>
  <div>
    <h2>Chat Messages</h2>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
  </div>
</template>

<script>
import Echo from "../echo"; // Import the Echo instance

export default {
  data() {
    return {
      messages: [],
    };
  },
  mounted() {
    window.Echo.channel("chat-channel")
      .listen(".message.sent", (event) => {
        this.messages.push(event.message);
      });
  },
};
</script>

## **6. Test the Broadcasting**
1. **Start Laravel Reverb**

php artisan reverb:start

2. **Run Laravel API**

php artisan serve

3. **Start Vue Application**

yarn dev

4. **Send a Test Message via API**

curl -X POST http://your-laravel-app.com/api/send-message -H "Content-Type: application/json" -d '{"message": "Hello World"}'

If everything is set up correctly, your Vue app should receive and display the message in real-time.

### **Final Notes**
– Ensure WebSockets are open in your firewall and server security groups.
– If hosted on AWS, configure the EC2 security group to allow traffic on port `6001`.
– You can extend this implementation by adding user authentication to private channels.

Let me know if you need adjustments!

User
Broadcast and event real-time example
Assistant
### **Real-Time Broadcasting and Events in Laravel with Vue.js**
This example demonstrates real-time event broadcasting in Laravel using **Reverb** (WebSockets) with an external **Vue.js** application.

## **1. Setup Laravel for Broadcasting**
### **Step 1: Install Laravel Reverb**
Since you're using Laravel 10+ and PHP 8.3, install Reverb for real-time broadcasting:

composer require laravel/reverb

### **Step 2: Publish Reverb Configuration**

php artisan vendor:publish --tag=reverb-config

Modify `.env`:

BROADCAST_DRIVER=reverb
REVERB_HOST=127.0.0.1
REVERB_PORT=6001

Start Reverb:

php artisan reverb:start

## **2. Create a Broadcast Event**
Generate an event:

php artisan make:event NewMessage

Modify `app/Events/NewMessage.php`:

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new Channel('chat-room');
    }

    public function broadcastAs()
    {
        return 'new-message';
    }
}

## **3. Fire Event from Laravel**
Create a `ChatController`:

use AppEventsNewMessage;
use IlluminateHttpRequest;

class ChatController extends Controller
{
    public function sendMessage(Request $request)
    {
        $message = $request->input('message');

        broadcast(new NewMessage($message))->toOthers();

        return response()->json(['message' => 'Broadcasted successfully']);
    }
}

Define API Route (`routes/api.php`):

use AppHttpControllersChatController;

Route::post('/send-message', [ChatController::class, 'sendMessage']);

## **4. Setup Vue.js with Laravel Echo**
Install dependencies in your Vue.js project:

yarn add laravel-echo pusher-js

Create an `echo.js` file:

import Echo from "laravel-echo";
import Pusher from "pusher-js";

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: "pusher",
    key: "reverb",
    wsHost: "your-domain.com", // Replace with your domain or localhost
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
    enabledTransports: ["ws", "wss"],
});

## **5. Listen for Real-Time Messages in Vue**
Modify your `ChatComponent.vue`:

<template>
  <div>
    <h2>Chat Room</h2>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
    <input v-model="newMessage" placeholder="Type a message" />
    <button @click="sendMessage">Send</button>
  </div>
</template>

<script>
import axios from "axios";
import "../echo"; // Import the Echo instance

export default {
  data() {
    return {
      messages: [],
      newMessage: "",
    };
  },
  mounted() {
    window.Echo.channel("chat-room").listen(".new-message", (event) => {
      this.messages.push(event.message);
    });
  },
  methods: {
    sendMessage() {
      axios.post("http://your-laravel-app.com/api/send-message", {
        message: this.newMessage,
      });
      this.newMessage = "";
    },
  },
};
</script>

## **6. Test Real-Time Broadcasting**
1. **Start Laravel Reverb**:

php artisan reverb:start

2. **Run Laravel API**:

php artisan serve

3. **Run Vue App**:

yarn dev

4. **Send a Message**
Open the chat in multiple tabs and type a message. The message should appear in real-time across all tabs.

### **Final Notes**
– Ensure WebSockets (port `6001`) are open in your firewall or AWS security group.
– If using Laravel authentication, switch to **private channels** with authentication.

Let me know if you need enhancements!

Leave a Comment

Your email address will not be published. Required fields are marked *