How To Cache Database Query Using Laravel Cache?

Reading Time: 5 minutes
339 Views

Caching database queries is a powerful strategy for improving Laravel application speed by minimising database load. We will walk you through the process of caching database queries using Laravel’s built-in caching system in this tutorial. This lesson is intended for all skill levels, whether you are a beginner or an experienced Laravel developer.

When your programme frequently requests the database for the same information, caching allows you to temporarily store the responses. Subsequent requests for the same data can then be served directly from the cache, eliminating the need to repeatedly access the database.

Laravel provides Cache facade to cache data in laravel. We will use put(), get(), remember(), rememberForever(), forget() and flush() method of Cache facade to cache data.

Read More: How To Remove Item by Value From Laravel Collection

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Database Cache Settings

Open .env file from project root.

CACHE_DRIVER=file

You can also use and set to redisfile, and database.

Laravel Cache Query Result Using “put()” and “get()”

In any of your controller, you can use this concept:

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Cache;
     
class PostController extends Controller
{
    public function index(Request $request)
    {
        $seconds = 60;
        $posts = Post::get();
        Cache::put('posts', $posts, $seconds);
  
        return view('posts', compact('posts'));
    }

    public function getPosts($id)
    {
        $posts = Cache::get('posts');
  
        dd($posts);
    }
}

Laravel Cache Query Result Using “remember()”

The remember() method in Laravel is used to cache the result of an expensive action or query for a set duration of time. This can be quite effective for reducing server load and speeding up response time for frequently accessed data.

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Cache;
     
class PostController extends Controller
{
    public function index(Request $request)
    {
        $seconds = 60;
        $posts = Cache::remember('posts', $seconds, function () {
            return Post::get();
        });
  
        return view('posts', compact('posts'));
    }
}

Laravel Cache Query Result Using “rememberForever()”

The rememberForever() method in Laravel is used to cache the result of an action indefinitely, which means that the cached data will not expire unless you actively remove it or empty the entire cache.

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Cache;
     
class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Cache::rememberForever('posts', function () {
            return Post::get();
        });
  
        return view('posts', compact('posts'));
    }
}

Read More: How To Add Digital Signature To PDF in Laravel 10 Tutorial

Dynamically, Cache Query Result Using “rememberForever()”

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Cache;
     
class PostController extends Controller
{
    public function show($id)
    {   
        $post = Cache::remember('post-'.$id, function ($id) {
            return Post::find($id);
        });
  
        return view('show', compact('post'));
    }
}

Laravel Cache Clear Using “forget()” and “flush()”

To clear cached data in Laravel, use the forget() method to remove specified items from the cache and the flush() method to clear all cached data.

<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Cache;
     
class PostController extends Controller
{
    public function remove()
    {   
        /* Remove a specific item from the cache */
        Cache::forget('cache-key');
	    
        /* Clear all cached data */
	    Cache::flush();
    }
}

That’s it.

We hope this article helped you to learn about How To Cache Database Query Using Laravel Cache Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.