Laravel Horizon simplified [In-Depth Tutorial]


Laravel

Author: Steve Alila
Reviewer: Deepak Prasad

Laravel Horizon is a powerful tool for managing and monitoring queues in Laravel applications. It provides an intuitive and user-friendly interface for managing queue workers and monitoring queue performance.

Laravel Horizon provides a beautiful, real-time user interface for monitoring and managing queues in Laravel applications. With Horizon, you can easily monitor the status of your queues, view detailed job information, and configure various settings related to your queues.

Horizon allows you to manage multiple queue workers for your Laravel application easily. You can define multiple queues with different priorities and manage how many workers are running for each queue. You can also configure other settings, such as the maximum number of retries for failed jobs and the maximum number of jobs that can be processed in a single worker cycle.

This tutorial walks you through the installation, configuration, and usage of Laravel Horizon.

 

Installing Laravel Horizon

Requirements

You need the following requirements to install Laravel Horizon:

  • PHP: Laravel Horizon requires PHP 7.1.3 or higher. Therefore, you need to install PHP on your system to ensure it meets the minimum version requirements.
  • Composer: Laravel Horizon is installed using the Composer package manager. Therefore, you must have Composer installed on your system before installing Laravel Horizon.
  • Laravel Framework: Laravel Horizon is a package that runs on top of the Laravel PHP framework. Therefore, you must have Laravel installed on your system before installing Laravel Horizon. The recommended version of Laravel is 5.5 or higher.
  • Redis: Laravel Horizon uses Redis as its backend for managing queues. Therefore, you need to have Redis installed and configured on your system. The minimum required version of Redis is 3.2 or higher.
  • Supervisor (optional): If you plan to run multiple queue workers, using Supervisor to manage the worker processes is recommended. The Supervisor is a process control system that enables you to monitor and control processes on Unix-based operating systems.

 

Step-by-step Installation

Laravel

Before you can install Laravel Horizon, you need to have Laravel installed on your system. You can install Laravel using Composer by running the following command in your terminal:

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

Using composer, we have installed Laravel and have created a project called laravel_horizon and navigated into the new project directory.

Redis

For this demo, we will use Ubuntu 22.04. So, install Redis by running the following command:

sudo apt update
sudo apt install redis-server

Laravel Horizon

Once you have Laravel and Redis installed on your system, you can install Laravel Horizon using Composer. Run the following commands in your terminal:

composer require laravel/horizon
php artisan horizon:install

composer require laravel/horizon, is a command that uses Composer to install the Laravel Horizon package in the laravel_horizon project.

Laravel Horizon simplified [In-Depth Tutorial]

The php artisan horizon:install publishes the assets of the package Now you can find the primary configuration files in the config/horizon.php file. You can also configure your application's queue worker options in the file.

 

Configuring Laravel Horizon

One of the primary Horizon configuration options is environments. It houses an array of environments the application depends on and defines the worker process per environment.

  'environments' => [
        'production' => [
            'supervisor-1' => [
                'maxProcesses' => 10,
                'balanceMaxShift' => 1,
                'balanceCooldown' => 3,
            ],
        ],

        'local' => [
            'supervisor-1' => [
                'maxProcesses' => 3,
            ],
        ],
    ],

Supervisors manage a group of worker processes and balance the processes across queues.

There are three worker balancing strategies: simple (default), auto, and false. simple strategy splits the job evenly among worker processes. auto adjusts the number of work processes per queue depending on the queue's current workload. Lastly, false processes the queues in the order listed in your configuration.

By default, the Horizon Dashboard is accessible via the local environment and with any application user. You can change this behavior in the app/Providers/HorizonServiceProvider.php file's authorization's gate. For instance, you can restrict access to only users with the specified email addresses.

<?php
...
    /**
     * Register the Horizon gate.
     *
     * This gate determines who can access Horizon in non-local environments.
     */
    protected function gate(): void
    {
        Gate::define('viewHorizon', function ($user) {
            return in_array($user->email, [
                'johndoe@compny.net',
                'loremsmith@gmail.com',
            ]);
        });
    }
...

After configuring supervisors and workers in the config/horizon.php file, you can start Horizon.

php artisan horizon

The command starts all currently configured worker processes for the current environment. You can control worker processes with by appending the respective commands to the horizon command with a colon :. Here are some examples:

# The Horizon process' current status
php artisan horizon:status
# Terminate the Horizon process
php artisan horizon:terminate
# Pause the Horizon process
php artisan horizon:pause
# Continue the Horizon process
php artisan horizon:continue
# Delete a failed job (with id of 9)
php artisan horizon:forget 9
# Clear jobs from queues
php artisan horizon:clear

 

Using Laravel Horizon (Practical Example)

In this section, we will queue and manage email notifications with Horizon.

Configure Redis

Let's start by setting Redis as the default queue in .env file.

QUEUE_CONNECTION=redis

Next, install predis

composer require predis/predis

and configure it as the Redis Client in the .env file.

REDIS_CLIENT=predis

Laravel Horizon simplified [In-Depth Tutorial]

 

Configure email

Next, configure email testing with Mail trap then create email notification class using the following command.

php artisan make:notification EmailNotification

Open the class in the app/Notifications/EmailNotification.php file and let it implement ShouldQueue contract.

<?php
...
  use Illuminate\Notifications\Notification;
  use Illuminate\Contracts\Queue\ShouldQueue;

class EmailNotification extends Notification implements ShouldQueue
{
   	//...
}

Test Horizon

Seed 3 users and migrate the changes.

Laravel Horizon simplified [In-Depth Tutorial]

Now send an email notification to the second user by writing the following code in routes/web.php.

<?php

use App\Models\User;
use App\Notifications\EmailNotification;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    User::find(2)->notify(new EmailNotification());
    return 'Notification sent';
});

Start the development server and access / and /horizon routes.

Laravel Horizon simplified [In-Depth Tutorial]

Finally, start the worker process and Laravel Horizon to send the queued email notifications.

php artisan queue:work
php artisan horizon

Horizon is active and the queued emails are getting delivered.

Use Laravel Horizon

 

Conclusion

Laravel Horizon is a fantastic tool if you working with Laravel's queue system. With its intuitive dashboard and advanced features, Horizon simplifies the monitoring and management of queues, making it easier to identify and resolve issues quickly.

One of the significant advantages of using Laravel Horizon is its ability to handle the queue system's scalability. It can handle many jobs, distribute them across multiple workers, and monitor their progress in real-time.

Furthermore, Laravel Horizon's built-in job metrics and performance monitoring tools give detailed insights into the application's queue system's behavior. This data can help you identify bottlenecks, optimize your queues, and ensure that your application runs efficiently.

 

Views: 113
Steve Alila

Steve Alila

He specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, and data presentation using Matplotlib and Plotly. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment