How to use queue on custom class in laravel?

Member

by daisha , in category: PHP Frameworks , 5 months ago

How to use queue on custom class in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 5 months ago

@daisha 

To use a queue on a custom class in Laravel, you need to follow these steps:

  1. Create a custom class that you want to use with the queue. For example, let's create a custom class called CustomJob:
1
2
3
4
5
6
7
8
9
namespace AppJobs;

class CustomJob
{
    public function handle()
    {
        //do your processing here
    }
}


  1. Register your custom class in the Laravel service container by adding it to the $listen array in the EventServiceProvider class. Open the EventServiceProvider.php file located in the app/Providers directory and add the following code:
1
2
3
4
5
protected $listen = [
    'AppEventsCustomJob' => [
        'AppJobsCustomJob',
    ],
];


  1. Dispatch the custom class to the queue in your code. You can dispatch the custom class using the dispatch() helper method:
1
2
3
use AppEventsCustomJob;

dispatch(new CustomJob());


  1. Configure your queue driver in the .env file. You can use any queue driver supported by Laravel such as database, Redis, or Amazon SQS. Set the QUEUE_DRIVER variable in the .env file to the desired queue driver:
1
QUEUE_CONNECTION=database


  1. Run the queue worker to start processing the job. Open a terminal and run the following command to start the queue worker:
1
php artisan queue:work


Your custom class will now be processed by the queue worker asynchronously.