How to Use Redis with Laravel?

Quick Summary:

Transform your Laravel application with Redis’s speed. Learn why Redis is a popular session and cache store for Laravel apps. How does Redis integrate so seamlessly? What data structures and features make Redis shine for Laravel use cases? How can Redis boost Laravel app performance and scalability? This blog post will thoroughly walk through the Redis and Laravel integration, answer these questions and more, and have your app faster than ever.

Have you ever wondered how Laravel’s top-performing web applications achieve enhanced performance and seamless user experience? Have you ever wondered what helps them achieve this lightning-fast speed? Enter Laravel Redis, an open-source advanced key-value store. Now imagine that your application delivers the content swiftly and handles caching, real-time data processing and much more with supreme efficiency. Laravel, a popular PHP framework, has joined hands with Redis, an advanced in-memory data structure store. Here, you might have questions like what is Redis for Laravel?

Redis, an open-source, in-memory data structure, serves as a high-performance cache, message broker, and key-value store. It enables rapid data retrieval, real-time analytics, and seamless application communication. Redis offers speed and high availability, but its main disadvantage is memory consumption, which may require large storage space for large datasets, which Redis Enterprise addresses.

Redis Cloud, also known as Redis Enterprise, is a cloud service that manages Redis datasets efficiently, allowing users to focus on application development. It offers free 30MB storage for beginners, but larger datasets require a paid plan. We will see this in the later part of the blog. Let’s first see how you can set up Laravel with Redis.

Together, they form a dynamic duo that uplifts the web application performance, Laravel, with its expressive syntax and comprehensive toolkit, blends seamlessly with Redis, providing developers with powerful tools to enhance the performance, scalability, and real-time capabilities.

 

Why use Redis with Laravel?

Laravel stands out with its integrated support for Redis, elevating it to preferred caching and session storage choices. Redis plays a significant role in boosting the speed of Laravel applications through efficient caching techniques. With Laravel automatically setting up Redis for both caching and session management, developers can enjoy a seamless and efficient experience.

As Redis is a data structure server, don’t think of it as basic storage tool, it offers much more than that. Its advanced structure includes sorted sets, and enables dynamic features like Laravel leaderboards. Apart from that Redis also integrates automatic serialization making it perfect for the Laravel apps. With its reliable compatibility, Redis effortlessly scales within Laravel environments, allowing applications to expand without effecting performance.

With Laravel Broadcasting, you can transform communication game. This feature utilizes the powerful Redis pub/sub mechanism to enhance the responsiveness and elevate user experience. Redis has proven itself a reliable technology that guarantees a smooth SDLC cycle. Redis’s trinity of user-friendliness, speed and reliability makes it a perfect complement for the performance optimization of Laravel application.

How to use Redis in Laravel?

Follow the following code to install Laravel with Redis.

Install Laravel

Before delving into the intricacies of Laravel Redis Integration, let’s ensure we have a solid Laravel foundation. Installing Laravel Breeze, thanks to the Composer, the PHP dependency manager. Let’s begin with the terminal.

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

Installing & Configuring Redis for Laravel

Once the Laravel is installed, the next step is to integrate Redis into the application. Laravel offers seamless integration to the Redis using the predis/predis library, which can be installed via the composer.

composer require predis/predis

Once done, you must configure laravel to use Redis as   your  cache driver. Open the .env file and then set the cache_driver variable to ‘redis’:

CACHE_DRIVER=redis

You will also need to configure the connection settings in the ‘config/database.php’ file under the ‘redis’ section.

'redis' => [
    'client' => env('REDIS_CLIENT', 'predis'),
    'default' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', 6379),
        'database' => env('REDIS_DB', 0),
    ],
],

Congratulations! You have successfully set up Laravel with Redis. Still after all this instruction you’re not sure whether you can do it yourself or not, Hire Laravel Developers who can leverage Redis and make most out of it.

How to Interact with Redis?

You have installed the Redis, now how can you interact with it? Let’s see.

To interact with Redis, you need to use the Redis façade.

use Illuminate\Support\Facades\Redis;

Redis façade supports dynamic methods, what it means is you can call any Redis method on façade and the command will directly pass to Redis. To understand it better, let’s look at the example, we will GET command by calling the get method on Redis.

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */    public function showProfile($id)
    {
        $user = Redis::get('user:profile:'.$id);
        return view('company.employee', ['user' => $user]);
    }
}

The Redis server receives commands from Laravel using magic methods, therefore pass the parameters that the Redis command expects:

Redis::set('company', 'Aglowid');
$values = Redis::lrange('company', 10, 50);

The command () function also allows you to send commands to the server. The first argument it takes is the name command, and the second is an array of values:

$values = Redis::command('lrange', ['name', 10, 50]);

Now that you have installed Redis for your project and understand how to interact with it let’s get into the fundamentals of Redis.

What Data Structures and Features make Redis Shine for Laravel Use Cases?

Following are the fundamentals that you need to keep in mind. Let’s begin with the key-value pair.

Key-Value Pair

At the heart of Redis lies the concept of key-value pairs. Redis allows you to store data with a unique key and retrieve it swiftly. Understanding this fundamental is important for effective utilization of Redis. Let’s understand it better with an example.

// Storing data in Redis
Redis::set('user:1:name', 'John Doe');
// Retrieving data from Redis
$name = Redis::get('user:1:name');
// Output: 'John Doe'
echo $name;

In this demonstration, we establish the ‘user:1:name’ key in Redis and assign it a ‘John Doe’ value. Later on, we access the corresponding value using the same key. This straightforward process perfectly encapsulates the concept of Redis key-value pairs.

Next, is Common Redis Data Types

Common Redis Data Types

 Redis offers a wide range of invaluable data types, each tailored for a specific use. From strings and lists to sets and hashes, You should anticipate seeing a wide range of essential types. By utilizing these data types effectively, you can greatly optimize your application’s performance and its capabilities. Here are some common Redis data types:

Strings

The powerful database system Redis offers a versatile range of data types. Among these, strings stand out as the simplest and most fundamental type, capable of holding various data forms such as plain text, numbers, and serialized information. Take a look at the example below.

// Setting a string value
Redis::set('counter', 8);
// Incrementing a numeric value
Redis::incr('counter');

Lists

What’s more, these strings can be organized into ordered collections known as lists, where one can easily add items to either the front or back. Consider the example below for a clearer understanding.

// Adding an item to the end of a list
Redis::rpush('recently_viewed_item', 'item:1');

Sets

sets offer another useful feature by allowing the storage of unique elements. This is particularly beneficial in cases where data must be one-of-a-kind. To illustrate, take a look at the example provided:

// Adding items to a set
Redis::sadd('tags:php', 'Laravel');
Redis::sadd('tags:php', ‘CodeIgniter’);

Hashes

The inventiveness of Redis extends to include hashes – a mapping between field of string and string values. As a result, hashes prove to be an excellent representation of objects

// Storing user data in a hash
Redis::hmset('user:1', [
    'name' => 'Alice',
    'email' => 'alice@example.com',
]);

By providing such diverse data types, Redis grants the flexibility to tailor data models according to the specific needs of an application. This ensures an optimal and efficient performance for any use case. These are just some of the commonly used data types, others include:

And you can get the information on official document.

Hey!✋
Are you looking to hire Laravel Developers?

Unlock lightning fast development with a Trusted Laravel development company’s professional developers at your service. Begin your quest today. @ Aglowid.

Get in touch

Basic Redis Operation Commands

Redis offers a plethora of commands to communicate with the data storage, while the Laravel Redis facade streamlines their implementation. Below are a few fundamental Redis commands and operations at your disposal; for better understanding, each is given as an example rather than a theory. It will include:

Setting & Getting Values

// Setting a key with a value
Redis::set(‘project:title', 'MyLaravelProject');
// Getting the value of a key
$title = Redis::get('project:title');

Expiring Keys

// Setting a key with an expiration time (in seconds)
Redis::setex('token:1234', 1800, 'user_token');

Incrementing & Decrementing

// Incrementing a numeric value
Redis::incr('ctr');
// Decrementing a numeric value
Redis::decr('ctr');

Working with Lists

// Adding an item to the end of a list
Redis::rpush('recently_viewed', 'item:1');
// Retrieving elements from a list
$recentlyViewed = Redis::lrange('recently_viewed', 0, -1);

Mastering the fundamentals of key-value pairs, delving into Redis’s versatile data types, and mastering fundamental commandswill open doors for more advanced procedures. These key components are essential for unlocking the full potential of Redis within Laravel applications by following laravel’s best practices. With a strong grasp on these building blocks, you’ll be fully equipped to harness the limitless possibilities of Redis in your Laravel projects.

Now that you are clear on the fundamentals of Redis, let’s look at the advanced concepts of Redis such as Performance Optimization in Redis.

How does Redis Integrate so Seamlessly?

The Redis CLI is an essential tool for developers, providing a direct and efficient way to interact with the advanced in-memory data store of Redis. It offers a powerful and versatile command-line interface, enabling users to execute Redis commands and operations easily. This makes it an invaluable resource for utilizing the full potential of Redis.

Redis CLI Features and Usage:

Redis CLI is deliberately crafted to offer users a seamless and effortless experience. Once connected to a Redis server via the command line, developers are granted a vast array of commands, empowering them to investigate, modify, and oversee their Redis data effortlessly.

Connecting to Redis

To connect with Redis server using Redis CLI, developers need to execute the following command simply:

redis-cli

Use this command to connect with  Redis server on your local machine. Alternatively, you can enter its IP address and port if you want to connect to a specific server.

redis-cli -h <hostname> -p <port>

Executing Command

Once users are connected, they can immediately execute Redis commands straight from the command line. An example is using the SET command to establish a key-value pairing

SET mydemo "Hi!"

Equally, you need to GET command for retrieving the value of a key

GET mydemo

Interactive Mode

Experience real-time responses by using the interactive mode of the Redis CLI. Unlike constantly restarting the CLI, developers can effortlessly enter commands in this mode. Simply run redis-cli without any arguments to activate it. Then, use the CLI to execute commands one after another.

Additional Options:

The Redis command-line interface provides numerous features to improve the overall user experience. For example, by using the -a option, individuals can input a password when connecting to a protected Redis server. Moreover, the CLI boasts the laravel security using its best practices, scripting, transaction monitoring, and pipelining functionalities, all of which offer developers advanced tools for effectively managing and optimizing their Redis instances.

The Redis CLI is a crucial tool in the arsenal of Laravel developers, serving as a powerful and seamless method of communicating with Redis servers. From essential tasks like troubleshooting and scripting to regular upkeep, the Redis CLI empowers developers to fully utilize the capabilities of Redis through a simple command line interface. For a comprehensive understanding of the Redis CLI and all its multifaceted capabilities, turn to the official documentation: Redis CLI Documentation.

How can Redis Boost Laravel App Performance and Scalability?

There are various ways in which Laravel Redis can help you perform optimization. They are as follows:

Redis benchmark

The Redis-benchmark command line tool is a versatile tool that allows you to simulate a variety of workloads, including write-heavy, read-heavy, and varying key/value sizes. Along with measuring throughput and latency, it also tracks metrics like requests per second, providing you with a comprehensive performance analysis. This tool is essential for establishing a performance baseline for your Redis setup and identifying the most effective configuration changes to optimize performance for your specific use case workloads.

Redis CPU profiling

Redis-floyd is a tremendously helpful tool for analyzing Redis and identifying which parts of the code are using excessive CPU. By regularly performing CPU profiling tests under various workloads, we can accurately pinpoint any slowdowns in the system. For example, if there is a spike in CPU usage during write operations, it could indicate a problem with the way data is being serialized. Similarly, an increase in CPU usage during key expiration may be a sign of an excessive number of useless keys. These bottlenecks can be addressed by adjusting the configuration settings or optimizing Redis Lua scripts, improving overall performance.

Diagnosing Latency Issues

By using the Redis LATENCY command, one can easily track any spikes in request latency and stay on top of any intermittent lags. This is crucial for managing capacity issues, as correlating these spikes with maxmemory limits being hit and eviction behavior can effectively diagnose any potential problems. Furthermore, when latency instances coincide with sudden surge in traffic, it’s imperative to investigate and determine if scaling up resources is necessary for optimal performance.

Redis Latency Monitoring

Turning on Redis LATENCY events allows for the acquisition of time series data on latency for a variety of commands. This information can then be seamlessly integrated into a monitoring system for easy analysis. Any sudden spikes can be quickly identified as potential problems by utilizing latency graphs. Additionally, implementing latency SLAs helps ensure that Redis performs at an acceptable level. By studying the distribution of latency for individual commands, valuable insights can be gained for optimization purposes.

Memory Optimization

Choosing the allkeys-lru option for the maxmemory policy ensures that only the least recently used keys are evicted, effectively preventing unnecessary keys from taking up valuable memory. This, along with properly setting and regularly monitoring the maxmemory limit, safeguards against any memory-related issues. Fine-tuning can also be done through the manipulation of key expiry times and imposing limits on key sizes. Keeping tabs on the rates of eviction and expired keys can offer valuable insights for further optimization.

Faster Database Queries

Redis offers more than just caching capabilities; it can also significantly enhance database query performance. By strategically utilizing Redis to store frequently used data, so that you can reduce the load on your database and drastically speed up query times.

Utilize Redis and Laravel Job Queues

Asynchronous processing is a critical component in developing scalable applications. By utilizing Laravel’s job queues, which Redis power, you can delegate time-intensive tasks to background processes and improve the overall responsiveness of your application.

Redis Pipelining

Pipelining is a powerful technique that allows multiple commands to be sent to Redis in one request, reducing the overhead of multiple round-trip communications. With Laravel’s support for this feature, you can greatly optimize your application’s performance.

Wrapping Up!

This brings us to the end of Laravel Redis integration by reviewing the fundamentals, including key-value pairs and other data kinds. We’ve navigated through key-value stores, diverse data types, and potent Redis commands. We explored Redis’ pivotal role in Laravel’s framework from caching excellence to real-time features. Whether optimizing performance through benchmarking, diagnosing latency issues, or memory optimization, Redis emerges as a key player for scalable and responsive applications.

Cutting Costs but
Not Cutting Quality

that’s how we roll! 🚀

Contact Us

This post was last modified on June 3, 2024 8:18 pm

Saurabh Barot: Saurabh Barot, the CTO at Aglowid IT Solutions, holds over a decade of experience in web, mobile, data engineering, Salesforce, and cloud computing. Renowned for his strategic vision and leadership, Saurabh excels in overseeing technology strategy, managing data infrastructure, and leading cross-functional teams to drive innovation. Starting with web and mobile application projects, his expertise extends to Big Data, ETL processes, CRM systems, and cloud infrastructure, making him a pivotal force in aligning technology initiatives with business goals and ensuring the company stays at the forefront of technological advancements.
Related Post