Laravel Caching: A Step by Step Guide to Setting Up and Using Cache

Laravel Caching

If you’ve started working with Laravel, sooner or later you’ll hear about Laravel Caching. At first, it may sound like an advanced optimization topic. In reality, caching is one of the simplest ways to make your application faster and more efficient even in a small local project.

In this beginner friendly guide, we’ll walk step by step through Laravel Caching, focusing on a practical Laravel cache setup using the File driver on Ubuntu/Debian. Let’s delve in.

Why Laravel Caching Matters

Every time a user visits your app, Laravel might do these actions immediately and for every process:

  • Run database queries
  • Perform calculations
  • Render Blade views
  • Load configuration files

If the same data is requested repeatedly, recalculating it every time wastes CPU and time. That’s where Laravel Caching helps. Instead of recalculating, Laravel stores the result temporarily and serves it quickly next time.

Even on a local machine, using laravel cache properly teaches you how to build scalable applications from the beginning.

What Is Cache? Understanding Drivers in Simple Term

A cache is temporary storage for data that is expensive or slow to compute. Laravel supports multiple cache drivers, each driver stores cached data in a different place. including:

  • File: Stores cache files in storage/framework/cache
  • Database: Stores cache in a database table
  • Redis/Memcached: Uses in-memory systems (very fast)
  • Array: Stores data only during the request lifecycle

For beginners, the File driver is perfect. It works out of the box and requires no additional services.

Prerequisites on Ubuntu/Debian

Before starting the Laravel cache setup, make sure you have:

  • PHP (8.1+ recommended)
  • Composer
  • Laravel project installed

Then go through steps.

  1. Install PHP (if needed)

Maybe you need to instal php first:

sudo apt update
sudo apt install php php-cli php-mbstring php-xml php-bcmath php-curl unzip
  1. Install Composer

This code simply do that for you:

sudo apt install composer

Or download from getcomposer.org if you prefer the official installer.

  1. Create a Laravel Project (if you don’t have one)
composer create-project laravel/laravel laravel-cache-demo
cd laravel-cache-demo
php artisan serve

Open http://127.0.0.1:8000 in your browser to verify.

Note: Exact PHP requirements may vary slightly depending on Laravel version, but recent versions follow similar steps.

Laravel Cache Setup (File Driver)

Now let’s configure the File driver properly.

Step 1: Configure .env

Open your .env file:

nano .env

Look for the cache setting. Depending on Laravel version, it might be:

CACHE_STORE=file

or

CACHE_DRIVER=file

Set it to:

CACHE_STORE=file

Save and exit.

If you’re unsure which variable your version uses, check config/cache.php.

Step 2: Check config/cache.php

Open:

nano config/cache.php

Look for:

'default' => env('CACHE_STORE', 'file'),

And verify the file driver exists:

'stores' => [
    'file' => [
        'driver' => 'file',
        'path' => storage_path('framework/cache/data'),
    ],
],

This confirms Laravel will store cache files locally.

Step 3: Verify Storage Permissions

Laravel needs write access to storage.

Run:

chmod -R 775 storage
chmod -R 775 bootstrap/cache

If using Apache:

sudo chown -R www-data:www-data storage bootstrap/cache

For local development using php artisan serve, this usually works automatically.

Your Laravel cache setup is now complete.

Practical Coding Examples

Now that the cache is properly configured, it’s time to see how it works in real code. These practical examples will show you how to store, retrieve, and manage cached data step by step.

First, import the Cache facade:

use Illuminate\Support\Facades\Cache;

Example 1: Cache::put and Cache::get

Cache::put('site_name', 'My Laravel App', 600);

$value = Cache::get('site_name');

echo $value;

The third parameter (600) is TTL (time to live) in seconds. That means 10 minutes. If the key doesn’t exist:

$value = Cache::get('unknown_key', 'Default Value');

Example 2: Cache::remember (Best Practice)

This is commonly used in real apps.

$users = Cache::remember('users_list', 300, function () {
    return \App\Models\User::all();
});

How it works:

  • If users_list exists → return cached data
  • If not → execute query, store result, return it

This avoids repeated database queries.

Example 3: Caching Heavy Calculations

$result = Cache::remember('expensive_calc', 120, function () {
    sleep(5); // simulate heavy work
    return 100 * 200;
});

First load: 5 seconds
Next loads: instant

TTL and Naming Tips

When working with cache, two small details can make a big difference: how long your data lives (TTL) and how clearly you name your keys. Choosing sensible expiration times and consistent key names keeps your cache predictable, manageable, and easier to debug later.

  • Use clear key names: user_1_profile, homepage_posts
  • Avoid generic names like data
  • Use consistent prefixes if your app grows

Example:

Cache::put('product:'.$id, $productData, 900);

Clearing Cache in Laravel

Sometimes you need to remove the cache manually. As you develop your application, there will be times when cached data needs to be refreshed or completely removed. Knowing how to properly clear cache in Laravel helps prevent confusion, outdated data, and those frustrating “why didn’t this update?” moments.

Laravel clear cache (Single Command) is:

php artisan cache:clear

This clears the application cache.

There isn’t a single “Laravel clear all” command, but developers often mean clearing everything that might be cached.

These commands help:

php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan optimize:clear

What each does:

  • cache:clear → clears application cache
  • config:clear → clears config cache
  • route:clear → clears cached routes
  • view:clear → clears compiled Blade views
  • optimize:clear → clears multiple caches at once

If something “doesn’t update,” clearing these usually fixes it.

Laravel Caching Strategies for Beginners

Caching is deciding what deserves to be stored and for how long. Good Laravel caching strategies help you balance performance with accuracy, especially in small projects. As a beginner, focus on simple, predictable rules instead of complex optimizations. The goal is to make your app faster without making your logic harder to maintain.

What should you cache:

  • Database query results
  • Expensive calculations
  • External API responses
  • Static content

What should you avoid caching:

  • Highly dynamic data (like live counters)
  • Sensitive temporary session data
  • Frequently changing data without invalidation logic

1. Avoiding Stale Data

Stale data means outdated data remains in cache. Caching improves performance but it also introduces one risk: showing outdated information. Understanding how to prevent stale data ensures your application stays both fast and accurate.

Solutions:

  • Use short TTL for frequently updated data
  • Manually clear cache after updates:
Cache::forget('users_list');

2. Cache Tags (Advanced Intro)

Some drivers (like Redis) support cache tags:

Cache::tags(['users'])->put('user_1', $data, 600);

File driver does NOT support tags. Keep this in mind if you plan to scale.

3. Debugging Tips

Even when caching is configured correctly, unexpected behavior can still happen during development. A few simple debugging habits can help you quickly identify whether the issue is in your logic or just in the cache:

  • Check storage/framework/cache/data
  • Log cache hits/misses
  • Temporarily reduce TTL during testing

Start simple. Add complexity later.

Upgrading to Redis (When and Why)

The File driver is perfect for learning and small projects, but it isn’t always the best long-term solution. As your application grows, you may need a faster and more scalable option this is where Redis becomes a practical upgrade.

You should consider Redis if:

  • Your traffic grows
  • You run multiple app instances
  • You need cache tags
  • You require faster performance

Basic steps:

  1. Install Redis server
  2. Install PHP Redis extension
  3. Set in .env:
CACHE_STORE=redis

You’ll also configure Redis in config/database.php. This is an upgrade path not required for beginners.

Laravel on a VPS Server (High Level Overview)

Running Laravel on a VPS server is similar to local setup but with extra considerations.

For example, if you deploy to an Ubuntu VPS, you must:

  • Ensure proper file permissions
  • Configure supervisor/queue workers
  • Possibly use Redis instead of File driver

If you’re setting up your server from scratch, this guide helps:

How to Install LAMP Server on VPS

If your audience is in Europe, infrastructure location may matter. Examples include:

On production VPS environments:

  • File cache works, but Redis is often preferred
  • Multiple servers require centralized caching
  • Permissions must be configured carefully

For beginners, keep learning locally first. Then migrate with confidence.

Conclusion

Laravel Caching is one of the easiest ways to improve performance without complex architecture changes. In this guide, you learned what cache is and how Laravel cache works, how to perform a complete Laravel cache setup using the File driver, and explored practical examples with Cache::put, Cache::get, and Cache::remember

You also saw how to handle Laravel clear cache and what developers mean by “Laravel clear all”, reviewed basic Laravel caching strategies, understood when to upgrade to Redis, and discovered what changes when running Laravel on a VPS server.

Start small. Cache one query. Observe performance. Then expand thoughtfully.

FAQ

What is Laravel Cache used for?

It stores frequently used data temporarily to reduce database queries and improve performance.

Which cache driver should beginners start with?

The File driver is simple, built-in, and perfect for small projects or learning.

How do I clear the cache in Laravel?
You can run php artisan cache:clear to remove all cached data.

When should I upgrade to Redis?

When your application needs higher performance, scalability, or handles heavy traffic.