Queues are data structures that hold data to be processed later. They follow the First-In-First-Out (FIFO) principle, meaning that the first job added to the queue is the first to be processed. Laravel Queues allow you to postpone time-consuming tasks such as sending emails, PDF generation, or data processing, thereby freeing up the application to respond quickly to user requests.
For example, consider an e-commerce application. When a user places an order, the application may need to process the order, send a confirmation email, update inventory, etc. Instead of making the user wait for all these tasks to complete, the application can add these tasks to a queue and respond immediately to the user, confirming their order. The tasks on the queue will then be processed in the background.
Let's walk through the process of setting up a Laravel project that includes a Queue job, and dispatching the job with the Order
class.
Open your terminal and navigate to your desired project directory. Run the following command to create a new Laravel project:
composer create-project --prefer-dist laravel/laravel LaravelQueueProject
Or by using:
laravel new LaravelQueueProject
Your project structure should be like this
Generate the necessary Queue job files using the php artisan
command. Run the following command in your terminal:
php artisan make:job ProcessOrder
This will create a new job file under the app/Jobs
directory named the ProcessOrder.php
After running the command above, your project structure should be like this.
Jobs
directory has been added into the app
directory.
Inside the app
directory, create a new file named the Order.php
. This class will represent an order and hold relevant attributes. Here’s a simple example of the Order
class:
// app/Order.php<?phpnamespace App;class Order{public $id;public $customer;// Add more properties and methods as needed}
ProcessOrder
jobNavigate to the app/Jobs
directory and add the given below code in the file named the ProcessOrder.php
. This job will process orders in the background queue and is set up to use tags for better management.
<?phpnamespace App\Jobs;use App\Order; // Import the Order classuse Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;class ProcessOrder implements ShouldQueue{use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;protected $order;// Add tags propertypublic $tags;public function __construct(Order $order){$this->order = $order;// Initialize tags with an array of tags$this->tags = ['order-processing', 'order-' . $order->id]; // Example tags}public function handle(){// Process the order...// You can add your order processing logic here}}
In your routes/web.php
file, set up a route that dispatches the ProcessOrder
job with an instance of the Order
class:
<?phpuse App\Jobs\ProcessOrder;use App\Order; // Import the Order classuse Illuminate\Support\Facades\Route;Route::get('/dispatch-job', function () {$order = new Order();$order->id = 123; // Replace with your order ID$order->customer = 'John Doe'; // Replace with customer informationProcessOrder::dispatch($order);return "Job dispatched!";});
After dispatching jobs to the queue, you need to run the queue worker to actually process these jobs. Open a new terminal window and navigate to your project directory. Run the following command to start the Queue worker:
php artisan queue:work
The Queue worker will continuously listen for new jobs and process them in the background. This is a crucial step in order to see your queued jobs being executed.
Start the Laravel development server by running:
php artisan serve
Access the URL http://localhost:8000/dispatch-job
in your browser to dispatch the ProcessOrder
job.
APP_NAME=Laravel APP_ENV=local APP_KEY=base64:Td5kZ3UuVVwhwxdU7sUKmnzloEhNLqRpY101o3TdCpM= APP_DEBUG=true APP_URL=http://localhost LOG_CHANNEL=stack LOG_DEPRECATIONS_CHANNEL=null LOG_LEVEL=debug DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=project_name DB_USERNAME=root DB_PASSWORD= BROADCAST_DRIVER=log CACHE_DRIVER=file FILESYSTEM_DRIVER=local QUEUE_CONNECTION=sync SESSION_DRIVER=file SESSION_LIFETIME=120 MEMCACHED_HOST=127.0.0.1 REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_MAILER=smtp MAIL_HOST=mailhog MAIL_PORT=1025 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null MAIL_FROM_ADDRESS=null MAIL_FROM_NAME="${APP_NAME}" AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= AWS_DEFAULT_REGION=us-east-1 AWS_BUCKET= AWS_USE_PATH_STYLE_ENDPOINT=false PUSHER_APP_ID= PUSHER_APP_KEY= PUSHER_APP_SECRET= PUSHER_APP_CLUSTER=mt1 MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
Laravel Queues are a powerful tool for improving application performance. By offloading time-consuming tasks to the queue, applications can respond faster, providing a better user experience.
Free Resources