Order Status Broadcasting

User
Broadcast and event with example of order status update
Assistant
### **Broadcasting and Events Example: Order Status Update in Laravel**

In Laravel, broadcasting events allow real-time updates to be sent to the frontend via WebSockets. Let’s go through an example where an **order status update** is broadcasted to the frontend.

### **1. Install and Configure Laravel Echo & Pusher**
If you haven't already installed the Pusher package, install it using Composer:

composer require pusher/pusher-php-server

Then, install Laravel Echo and Pusher on the frontend:

yarn add laravel-echo pusher-js

Update `.env` with Pusher credentials:

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https

Update `config/broadcasting.php`:

'connections' => [
    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'useTLS' => true,
        ],
    ],
],

### **2. Create an Event for Order Status Update**
Generate an event using Artisan:

php artisan make:event OrderStatusUpdated

This creates `app/Events/OrderStatusUpdated.php`. Modify it as follows:

namespace AppEvents;

use AppModelsOrder;
use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateBroadcastingPresenceChannel;
use IlluminateBroadcastingPrivateChannel;
use IlluminateContractsBroadcastingShouldBroadcast;
use IlluminateContractsBroadcastingShouldBroadcastNow;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;

class OrderStatusUpdated implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $order;

    /**
     * Create a new event instance.
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * Get the channels the event should broadcast on.
     */
    public function broadcastOn()
    {
        return new PrivateChannel('orders.' . $this->order->id);
    }

    public function broadcastAs()
    {
        return 'order.status.updated';
    }
}

This event will broadcast order status updates on a **private channel**.

### **3. Trigger the Event in the Controller**
Let's assume we update the order status in `OrderController.php`:

use AppEventsOrderStatusUpdated;
use AppModelsOrder;
use IlluminateHttpRequest;

class OrderController extends Controller
{
    public function updateStatus(Request $request, $id)
    {
        $order = Order::findOrFail($id);
        $order->status = $request->status;
        $order->save();

        broadcast(new OrderStatusUpdated($order))->toOthers();

        return response()->json(['message' => 'Order status updated successfully', 'order' => $order]);
    }
}

This triggers the **OrderStatusUpdated** event when an order's status is changed.

### **4. Listen to Events on Frontend (Vue.js)**
Inside `resources/js/app.js`:

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

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true
});

Inside your Vue.js component:

<template>
    <div>
        <h2>Order Status</h2>
        <p>Current Status: {{ orderStatus }}</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            orderStatus: 'Pending'
        };
    },
    mounted() {
        Echo.private(`orders.123`) // Replace with dynamic order ID
            .listen('.order.status.updated', (event) => {
                this.orderStatus = event.order.status;
                console.log('Order status updated:', event.order.status);
            });
    }
};
</script>

### **5. Authorizing Private Channels**
Modify `routes/channels.php` to allow only authenticated users to listen:

use IlluminateSupportFacadesBroadcast;

Broadcast::channel('orders.{orderId}', function ($user, $orderId) {
    return (int) $user->id === Order::find($orderId)->user_id;
});

### **Testing**
1. **Start Laravel queue worker (if using queues):**

php artisan queue:work

2. **Run Laravel WebSocket server:**

php artisan serve

3. **Update an order's status via API/Postman**:

PUT /api/orders/123
   Content-Type: application/json

   {
       "status": "Shipped"
   }

You should now see the order status update **in real-time** in your Vue.js component.

This setup ensures that any order status change is broadcasted to the frontend in **real time** using Laravel Echo and Pusher.

Leave a Comment

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