This two-part article series aims to make a beginner understand using push queues with Laravel. To give a brief overview, the final solution which we will be looking at is a simple form to upload photos and resize them. Resizing images is a time consuming task, so instead of making a user wait until the image is resized we can do it in the background. At the same time, we’ll learn to use a tool called ngrok so that we can use queues in our local system.

The source code is provided on GitHub.

You can also try it in a proper live server.

Queues and Iron

A queue is nothing but a pipeline where we line up our jobs and they are executed in the order they are inserted. Let’s say currently our queue is empty and we put Job A into it, then we put Job B and Job C. We read the queue in the same order. First we take Job A from the queue and finish it, and then work on next one. If you focus on the “read” part, we always have to check our queue to see if any new job is posted. Wouldn’t it be better if the queue itself notifies us when a job is available ? Queues like those are called push queues, and that’s what we’ll be using with IronMQ.

Iron MQ is a service which makes our life easier when it comes to using queues. When you create a push queue you also need to mention a subscriber to that queue. A subscriber is nothing but a URL which will be called when a job is available in the queue with the data originally provided to the job.

To read more about job queues and see comparisons between different solutions, see this article.

Setup and Installation

In this step we install Laravel and all required dependencies via composer. We also create an account at Iron and install a tool called ngrok.

Laravel

  1. Install Composer.

  2. Install Laravel

    composer create-project laravel/laravel --prefer-dist

    After this command you should see the folder “laravel”. Open the laravel folder in your favorite text editor or IDE.

    Go into the folder via the command line and run:

    php artisan serve

    At this point if you open http://localhost:8000 you should see the home page of your Laravel installation.

  3. Set up the Database : We will use MySQL for our database. Create a database via the command line, phpmyadmin, or whichever tool you are comfortable with. After you created a database, go to app/config/app.php and find the section similar to the following:

    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'root',
        'password'  => '',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    )
    

    Fill in the required fields. Assuming you are on a local system, you need to provide the credentials of your MySQL server (username, password) and the name of the database you created.

    Run php artisan migrate:install. If you have put your credentials correctly it should say: Migration table created successfully.

  4. Let’s make a small edit. Open app/views/hello.php and find the following line:

    <h1>You have arrived.</h1>
    

    Edit it to (You can change it to anything!):

    <h1>I am learning how to use queues!</h1>
    

    If you open http://localhost:8000 you should be able to see the Laravel logo and some text under it reading: “I am learning how to use queues!”.

  5. Open composer.json, add iron (for iron push queues) and intervention (for image manipulation) libraries.

    "require": {
        "laravel/framework": "4.1.*",
        "iron-io/iron_mq": "1.4.6",
        "intervention/image": "dev-master"
    },
    

    Update the code

    composer update
    
  6. Follow instructions below to finish installation of Intervention.

    Open your Laravel config file config/app.php. In the $providers array add the service providers for this package: 'Intervention\Image\ImageServiceProvider', then add the facade of this package to the $aliases array: 'Image' => 'Intervention\Image\Facades\Image',

    Reference: http://intervention.olivervogel.net/image/getting_started/laravel

ngrok

In production users access your website via a URL like http://example.com. But, you all know that our localhost is not available to the whole internet and as we are going to use Iron for implementing queues, we need to host our code in a server so that our website is accessible to Iron. Doing that means, every time we make a change to our code we have to upload it to the server and test to see if it is working as we intended. Wouldn’t it be better if we could test our code on a local system? That’s why we use a tool called ngrok which makes our localhost accessible to the whole internet via a special URL. We will be installing and using it in a second.

  1. Go to ngrok.

  2. Download and Install ngrok. Follow – How to install ngrok.

    The steps are:

    • Download the zip file for your operating system.
    • Unzip the downloaded zip file
    • You should be able to run ./ngrok --help from the command line.
  3. Let’s make our localhost visible on the internet.

    For this step we assume Laravel is still running at http://localhost:8000. (If it’s not, run php artisan serve from the command line at the root of the Laravel folder)

    (You need to run the ngrok command through another terminal as in one terminal php artisan serve needs to be running)

    ./ngrok 8000
    

    I have given port as 8000 since our laravel is running on 8000. After I run the command I get a reply:

    Tunnel Status                 online                                            
    Version                       1.6/1.5                                           
    Forwarding                    http://953ffbb.ngrok.com -> 127.0.0.1:8000        
    Forwarding                    https://953ffbb.ngrok.com -> 127.0.0.1:8000       
    Web Interface                 127.0.0.1:4040                                    
    # Conn                        2                                                 
    Avg Conn Time                 167.38ms 
    

    Note: The response you get is different every time you run ngrok. So, the response which you see after running ./ngrok 8000 will be different from what I posted above.

    Observe the URL under “Forwarding” : http://953ffbb.ngrok.com. If you open that URL (which is a different URL for you) you should be able to see your website with the Laravel logo and the text you have written, e.g.: “I am learning how to use queues!”.

    I suggest you keep ngrok running and note down the Forwarding URL as we are going to use it for this tutorial.

    If you happen to restart ngrok in between, your URL will change. It’s not at all a problem! Just make use of the different URL wherever needed.

Iron MQ

We will use Iron for implementing queues in our project. To use Iron we first need to create an account.

  1. Go to http://www.iron.io/ and log in

  2. Create a new project. I have named my project “Laravel Queues”.

  3. You can see a “Key” button right next to your project name. Click on it and copy “Token” and “Project ID” to app/config/queue.php.

    • Change default to ‘iron’

      'default' => 'iron',
      
    • Find the below section:

      'iron' => array(
          'driver'  => 'iron',
          'project' => 'your-project-id',
          'token'   => 'your-token',
          'queue'   => 'your-queue-name',
      )
      

      Copy your Project ID and Token from the dashboard and paste them here, name your queue “laravel”.

      'iron' => array(
          'driver'  => 'iron',
          'project' => 'your-project-id',
          'token'   => 'your-token',
          'queue'   => 'laravel',
      )
      
  4. As discussed above we need to add a subscriber for our queue. You can go to Laravel Push Queues and check the official documentation which we are going to follow now:

    • We have to register a push queue subscriber using the following artisan command (We have to run this command from our project root folder)

      From above reference, we will run php artisan queue:subscribe laravel http://953ffbb.ngrok.com/queue/receive

      Note that the URL I used was the Forwarding URL which ngrok generated. You should see a reply similar to the one below:

      Queue subscriber added: http://953ffbb.ngrok.com/queue/receive

      If you check your dashboard and click on “MQ” you will go to the project page. Click on “Queues” and find a queue named “laravel”. If you click on a queue name, i.e. laravel, you can see a list of subscribers in the Push Queues tab and find http://953ffbb.ngrok.com/queue/receive under it.

    • Put this code in app/routes.php

      Route::post('queue/receive', function()
      {
          return Queue::marshal();
      });
      

From the official documentation:

The marshal method will take care of firing the correct job handler class. To fire jobs onto the push queue, just use the same Queue::push method used for conventional queues.

Wrapping Up

In this part:

  1. We have installed Laravel with Iron and Intervention libraries. Our laravel is running at http://localhost:8000

  2. We installed ngrok and we exposed our localhost to the whole internet via a Forwarding Url that was generated for us (let ngrok run in the terminal).

  3. We configured Iron with Laravel and created a queue with a subscriber.

In the next part, we’ll do the heavy lifting and get our hands dirty. We’ll be building our app and implementing the job logic fully. Stay tuned!

Frequently Asked Questions about IronMQ Laravel Setup

What is IronMQ and why is it important for Laravel?

IronMQ is a highly scalable and flexible message queue service that allows for asynchronous communication between different parts of a software application. It is important for Laravel because it provides a simple, fast, and reliable solution for handling background jobs, thus improving the overall performance and efficiency of Laravel applications.

How do I install IronMQ in Laravel?

To install IronMQ in Laravel, you need to first install the IronMQ package via Composer. Then, you need to configure the queue settings in the Laravel configuration file. Finally, you need to set up the IronMQ service provider and facade in the Laravel application.

How do I configure IronMQ in Laravel?

Configuring IronMQ in Laravel involves setting up the queue connection details in the Laravel configuration file. This includes the host, queue name, token, and project ID. You also need to set the queue driver to ‘iron’ in the .env file.

How do I use IronMQ for handling background jobs in Laravel?

To use IronMQ for handling background jobs in Laravel, you need to create a job class that implements the ShouldQueue interface. Then, you can dispatch jobs to the IronMQ queue using the dispatch method.

What are the benefits of using IronMQ in Laravel?

Using IronMQ in Laravel offers several benefits. It provides a scalable and reliable solution for handling background jobs, thus improving the performance and efficiency of Laravel applications. It also offers advanced features like message delay, message expiration, and message prioritization.

How do I troubleshoot common issues with IronMQ in Laravel?

Troubleshooting common issues with IronMQ in Laravel involves checking the queue connection details, ensuring that the IronMQ service provider and facade are correctly set up, and verifying that the job classes are correctly implemented.

How do I monitor the status of IronMQ queues in Laravel?

You can monitor the status of IronMQ queues in Laravel using the Iron.io dashboard. This provides real-time information about the number of messages in the queue, the rate of message processing, and the status of individual messages.

How do I handle failed jobs with IronMQ in Laravel?

Laravel provides a built-in mechanism for handling failed jobs. If a job fails, it will be automatically retried a certain number of times. If it continues to fail, it will be moved to the failed jobs table.

How do I secure IronMQ in Laravel?

IronMQ provides several security features, including SSL/TLS encryption, IP whitelisting, and API key authentication. You can also secure your IronMQ queues by setting up access controls in the Iron.io dashboard.

How do I scale IronMQ in Laravel?

IronMQ is designed to be highly scalable. You can easily scale up your IronMQ queues by increasing the number of worker processes or by using the Iron.io autoscaling feature.

Rajiv SeelamRajiv Seelam
View Author

Rajiv is an enthusiastic web developer and product developer. He is a Computer Science Engineer from India. He loves PHP and has a deep affection for Laravel. He loves exploring new technologies. In his free time he reads technical articles written for PHP and tries to contribute to the community.

frameworkironmqlaravelmessage queuemqPHPqueue
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week