Table of contents
Do you need to process tasks in the Laravel 9 project via background? Usually for large-scale applications that have a huge task like sending emails or uploading big files it could consume a lot of time before it will be finished. And you don't want that your user will wait until the task will successfully process. That's why Laravel provides a queueing method in which you can process your task in your background with the use of Laravel Supervisor. Then you just notify your user that your task has been successfully processed.
Â
In this tutorial, you will be able to learn how to set up the Laravel 9 supervisor and Laravel queue with the database.
Â
Â
Step 1: Laravel 9 Supervisor Setup with Example
We have so many options in Laravel queue connection such as amazon sqs, redis, or even database. But in this example, we are using the database.
Â
To start kindly run the following command:
// to generate jobs table in migrations
php artisan queue:table
// then run migrate after the jobs migrations generated
php artisan migrate​
Â
Â
Step 2: Setup Laravel Supervisor
In this section let's assume that you have an ubuntu server already and let's set it up so that the Laravel queue will work using supervisor. The supervisor will run automatically in the background from your server and keep watching your active jobs and processing them until it has been done.
Â
To configure the supervisor you need to open your Linux terminal window and run the following command:
//update dependencies and install supervisor
sudo apt update && sudo apt install supervisor
//check supervisor status after the installation
sudo systemctl status supervisor
Â
Output:
Â
As we can see our supervisor is now active. So let's configure our Laravel project file for our supervisor worker.
# then navigate supervisor config folder
cd /etc/supervisor/conf.d
# then create Laravel project configuration file
sudo nano project-name-worker.conf
Â
Then paste the below code:
[program:project-name-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/project-name.com/public_html/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=ubuntu
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/project-name.com/public_html/storage/logs/worker.log
stopwaitsecs=3600
Â
Then save changes using Ctrl + X + Y + Enter
.
Â
NOTES:
1. Be sure that you input your exact project directory for replacing /var/www/project-name.com/public_html
.
2. user
value must be your logged user name. In my case is ubuntu.
3. and also the stdout_logfile change it to your project directory.
Â
Once you saved the changes. Let's run the following command:
Â
//to read the new supervisor configurations
sudo supervisorctl reread
//then activate the new configuration
sudo supervisorctl update
//to start the queue command
//take note that this is the name of our config file above.
//You can change it depending on your project name.
sudo supervisorctl start project-name-worker:*
//then check status if configured correctly
sudo supervisorctl status
Â
Another method is this:
// it will stop all queue
sudo supervisorctl stop all
// then read new configuration
sudo supervisorctl reread
// then update so that it will activate then newly added
sudo supervisorctl update
// then start all queues
sudo supervisorctl start all
// then check status
sudo supervisorctl status
Â
Now our supervisor is successfully configured. Now let's do the other steps.
Â
Â
Step 3: Setup Laravel Queue
Now let's do the Laravel queue so that it can be integrated with our supervisor setup above to do the testing.
Â
So in this example, let's say you have user management and the admin can invite users via email. So let's implement the Laravel queue on this so that the user invitation will run in the background.
Â
Then the following command:
php artisan make:job UserInvitationJob
Â
After running the above command it will generate a file app/Jobs/UserInvitationJob.php
with the following code:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class UserInvitationJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
}
}
Â
Now we have our UserInvitationJob
class for our Laravel queue user invitation. Next, we will update user UsersController.php
for our invitation or create a new user and then send the invitation.
Â
Here is the code below:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests\StoreUserRequest;
class UsersController extends Controller
{
/**
* Store a newly created user
*
* @param User $user
* @param StoreUserRequest $request
*
* @return \Illuminate\Http\Response
*/
public function store(User $user, StoreUserRequest $request)
{
//For demo purposes only. When creating user or inviting a user
// you should create a generated random password and email it to the user
$user = $user->create(array_merge($request->validated(), [
'password' => 'test'
]));
dispatch(new \App\Jobs\UserInvitationJob($user));
return redirect()->route('users.index')
->withSuccess(__('User created successfully.'));
}
}
Â
As you can see we added dispatch(new \App\Jobs\UserInvitationJob($user));
code which is we use to invite user and implement it with Laravel queue.
Â
Then in our UserInvitationJob
class, we will update the code to send the email invitation and run it through the background with the Laravel supervisor.
Â
<?php
namespace App\Jobs;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
class UserInvitationJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $user;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$userDetails = $this->user;
//send email invitation here
}
}
Â
After all, our Laravel supervisor and Laravel queue are ready. You can integrate it with your own functionalities. But before we do that don't forget to update the ENV config for the QUEUE_CONNECTION
value.
QUEUE_CONNECTION=database
Â
That's pretty much it. And now your Laravel supervisor implementation is running smoothly. I hope it helps.
Read next