Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to subscribe for Redis Pub/Sub in Laravel?

I've been using Redis's Pub/Sub a bit in my application and so far it has been great. I am able to send out a Publish out of Laravel to a different backend process that is able to Subscribe, and eventually Publish an event back to Laravel.

The use case for the user looks like:

submit a form -> wait for a response (a few minutes) -> proceed with transaction

On the backend:

the form posts to a route, then to a controller that publishes this to a subscribed 3rd party (channel one), and eventually that 3rd party publishes back (channel two)

Main Issue: I don't know where the appropriate place to be for subscribing to the (channel two) and processing what gets published there.

Ideally, I'd be able to process Publish requests in two ways:

  1. Letting the user know that their form has been processed and they can move onto the next step (probably with an update to a property a Vue component)

  2. Storing information from the publish into my database.

In the docs, they have it in a Command, which if I try to use here would look like so:

public function handle()
{
    Redis::subscribe('channel-two', function ($message) {
        // update the client so that the user moves on
        // send $message contents to the database
    });
}

but that doesn't really seem ideal for me since I want this channel subscribed to 24/7, always listening. Even if it is in a Command, it is still apparent how I would best update the client.

Where in my Laravel project should I be subscribing at? Is there a best practice to respond to these events?

like image 857
MintMelt Avatar asked Sep 14 '25 14:09

MintMelt


1 Answers

Redis::subscribe is used in a command like in that example for listening on a given channel continuously.

From the docs:

First, let's setup a channel listener using the subscribe method. We'll place this method call within an Artisan command since calling the subscribe method begins a long-running process:

You'll want to run the command using a process manager like supervisor or pm2, much the same as the docs describe running queue listeners.

like image 180
Brian Lee Avatar answered Sep 16 '25 09:09

Brian Lee