Back to Homepage

Best Practices for Caching in Laravel

3 min read

Tags:

Best Practices for Caching in Laravel

Caching data is very important to increase speed and reduce server response. A highly efficient web application is characterized by its fast content delivery. In the Laravel framework, caching is a useful tool that can greatly enhance your application's speed by reducing the frequency of direct database queries. This not only results in quicker response times but also reduces the workload on your database. In this article, we will discuss some recommended approaches for caching in Laravel and how you can easily incorporate it to optimize your application.

I faced the same problem: every time a bot or visitor tried to visit a page, the system executed a database query, even when the data didn't change. Let's talk about caching and best practices to get better results.

Understanding the Different Caching Drivers

There are several cache drivers supported by Laravel:

  • The File Cache is useful for small-scale applications. It stores cached items as files.

  • Cache: Stores cached items in a database table. Good for applications with small datasets.

  • In-memory data structures like Redis and Memcached. Ideal for high-demand applications with large datasets.

  • Redis or Memcached are often recommended for high-performance applications but for a normal application disk cache would work perfectly fine.

Configuration of the cache

It is important to set up your cache configuration correctly before you start caching. This is usually done in the .env file:

CACHE_DRIVER=disk

Heavy queries should be cached

For example, if you have a navigation menu that's derived from a database, but only changes occasionally, why query the database every time?

public function getMenusProperty()
{
    return Cache::remember('header_menu', 1440, function () {
        $menus = Menu::all();

        $menus->map(function ($menu) {
            $menu->setRelation('menuItems', MenuItem::treeOf(fn($query) => $query->isRoot()->where('menu_id', $menu->id))->get()->toTree());
        });

        return $menus;
    });
}

The menu is cached for 86400 seconds (24 hours). If the menu changes within that time, you can manually flush the cache or wait for it to refresh.

Use cache tags with drivers that support them

Cache tags can be invaluable for complex applications. They allow you to tag related items with a given tag, then flush all cached items with that tag. Note that file, array, and database cache drivers all support this feature.

Cache::tags(['posts'])->put('recent', $recentPosts, 3600);

later if you want delete cache

Cache::tags('posts')->flush();

Make use of route caching

You may want to consider route caching if your application consists of numerous routes. This can drastically speed up registration. However, this is only suitable for applications with routes that don't change frequently.

php artisan route:cache

Keep an eye out for changes to the model

In scenarios where data changes can impact the cache, use Laravel’s events and listeners. For example, if a new blog post is created, you might want to clear the cache for your list of recent posts.

Conclusion

It is important to understand your data and the frequency at which it changes in order to utilize Laravel's caching system properly. A quick user experience can be provided without overburdening your database if you carefully select what to cache and for how long, and if you are proactive about invalidating stale cache data.

Follow @LaravelSage on X → Follow @LaravelSage on Facebook →
Aniket Singh

Aniket Singh

View All Articles

Full-stack developer with a knack for Merging creativity with technical expertise for standout solutions.

Related Articles

Top Laravel Packages for Building Powerful Applications

Top Laravel Packages for Building Powerful Applications

Are you ready to take your Laravel skills to the next level and build extraordinary applications? Look no further! In this blog post, we will unveil a treasure trove of top packages that will revolutionize your development process.

MarkdownX:  Markdown Editor by DevDojo

MarkdownX: Markdown Editor by DevDojo

It's a lightweight markup language used by developers, writers, and content creators for formatting text for various purposes, such as documentation, blog posts.

Subscribe for 20+ new Laravel tutorials every week

You can unsubscribe at any time. You'll also get -20% off my courses!

© 2024

 

Laravel Sage

   |    Privacy Policy