Laravel: Queue

Laravel is using Jobs to encapsulate the message.

To send a message to the queue first you need to create Job class:

php artisan make:job TestJob
INFO Job [app/Jobs/TestJob.php] created successfully.

You will get a class with _construct() and handle() method.

To send a message you only need to focus on the _construct() method.

If you want to send a payload with name and age you will need to add them as the properties to the class.

private $name;
private $age;

public function __construct($someName, $someAge)
{
  $this->name = $someName;
  $this->age = $someAge;
}

You will need to trigger it by calling:

TestJob::dispatch('John', 25);

To process the queue, you will need to call:

php artisan queue:work

This will pop the queue and process it with the handle() method. But first it will need to map the payload to some variables. The variables name need to match the name of the payload.

private $name;
private $age;

public function handle(): void
{
  // Process the payload
}

NB: If you dispatch a message from one micro-service to another, then both micro-services need to have Job class with the same name and path (namespace).

References:


Comments

Leave a Reply

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