askingtoomuch
askingtoomuch

Reputation: 537

Laravel websocket to broadcast periodically

I would like to know if there's other appropriate way to achieve below in Laravel ~7.

Purpose: To update fast-selling product quantities every minute on the frontend (client) in real time.

Method: Use a scheduler to get the product quantity from the database and use websocket to broadcast it every minute.

Question: Is there any other better way to achieve this?

Event broadcast (backend)

// app/Events/ProductQuantity.php

class ProductQuantity implements ShouldBroadcast
{
    public $product;

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

    public function broadcastWith()
    {
        return ['quantity' => $this->product->quantity];
    }

    public function broadcastOn()
    {
        return new Channel('store');
    }

}

StoreFrontend (client)

<script>
    Echo.channel('store')
    .listen('ProductQuantity', (e) => {
        console.log(e.quantity);
    })
</script>

Upvotes: 0

Views: 397

Answers (1)

James
James

Reputation: 16359

Possibly...

Currently it sounds like you are effectively "polling" your database for the quantity of a product and then emitting this to your frontend with websockets. This is no different from using traditional polling techniques to hit an endpoint and request the latest quantity.

A better solution, in my opinion, would be to raise an event whenever the quantity of your product changes (either sold or stock is replenished). You can then hook this event up to broadcast to your frontend.

The result is that your frontend is notified whenever the stock changes, as opposed to needlessly polling every minute. It gives you the benefit that you don't need to hammer your database every minute on the scheduler to see if any data has changed, and the ability to immediately update your UI whenever the stock for a product changes.

Upvotes: 2

Related Questions