DEV Community

Cover image for Caching in Laravel & PHP
Ahmed Raza Idrisi
Ahmed Raza Idrisi

Posted on

Caching in Laravel & PHP

Great question πŸ‘ Let’s cover caching in PHP (raw) and then how Laravel makes it much easier and powerful.


🧠 1. What is Caching?

Caching means storing data temporarily so you don’t need to recalculate or refetch it every time.

  • Speeds up performance πŸš€
  • Reduces database/API load
  • Stores in memory (Redis/Memcached) or files

🐘 2. Caching in Plain PHP

In raw PHP, you don’t have a built-in cache system like Laravel, but you can implement simple ones.

Example 1: File-based Cache

<?php
function getCache($key) {
    $file = __DIR__ . "/cache/{$key}.txt";
    if (file_exists($file) && (time() - filemtime($file) < 60)) {
        // valid cache for 60 sec
        return file_get_contents($file);
    }
    return null;
}

function setCache($key, $data) {
    $file = __DIR__ . "/cache/{$key}.txt";
    file_put_contents($file, $data);
}

// Example: Caching API result
$data = getCache("users");

if (!$data) {
    echo "Fetching fresh data...\n";
    $data = json_encode(["Ahmed", "Ali", "Sara"]);
    setCache("users", $data);
} else {
    echo "Using cache...\n";
}

echo $data;
Enter fullscreen mode Exit fullscreen mode

βœ… First time β†’ fetches fresh data
βœ… Next times (within 60 sec) β†’ returns cache


Example 2: Memory Caching with APCu (if installed)

<?php
apcu_store('name', 'Ahmed', 60); // store 60 sec
echo apcu_fetch('name'); // Ahmed
Enter fullscreen mode Exit fullscreen mode

🎯 3. Caching in Laravel (Much Easier!)

Laravel comes with a powerful cache system out of the box.
Supported drivers: file, database, array, redis, memcached.
Default in .env:

CACHE_DRIVER=file
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Basic Cache Usage

use Illuminate\Support\Facades\Cache;

// Store
Cache::put('name', 'Ahmed', 60); // 60 seconds

// Retrieve
$name = Cache::get('name'); // Ahmed

// Retrieve with default
$name = Cache::get('username', 'Guest');

// Check
if (Cache::has('name')) {
    echo "Cache exists!";
}

// Delete
Cache::forget('name');
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Remember Pattern

Very common in Laravel:

$users = Cache::remember('users', 60, function () {
    return DB::table('users')->get();
});
Enter fullscreen mode Exit fullscreen mode

➑️ First time β†’ runs the DB query, caches it for 60 sec
➑️ Next time β†’ pulls from cache directly


πŸ”Ή Forever Cache

Cache::forever('site_settings', ['theme' => 'dark']);
Enter fullscreen mode Exit fullscreen mode

Remove it:

Cache::forget('site_settings');
Enter fullscreen mode Exit fullscreen mode

⚑ 4. Real-World Example: API Caching

public function getWeather() {
    return Cache::remember('weather_data', 600, function () {
        $response = Http::get('https://api.weatherapi.com/v1/current.json?key=API_KEY&q=London');
        return $response->json();
    });
}
Enter fullscreen mode Exit fullscreen mode

βœ… Saves API response for 10 minutes.
βœ… Avoids calling external API every time.


πŸ”” 5. Best Practices

  • Use Redis for high-performance caching in production.
  • Use remember or rememberForever instead of manually managing put/get.
  • Clear cache safely:
  php artisan cache:clear
Enter fullscreen mode Exit fullscreen mode
  • For config caching:
  php artisan config:cache
Enter fullscreen mode Exit fullscreen mode

βœ… In short:

  • In PHP, you can use files or APCu for caching.
  • In Laravel, use Cache facade β†’ simple and powerful (DB, Redis, Memcached, File).
  • Perfect for speeding up DB queries, API calls, or expensive calculations.

Perfect πŸ‘Œ Redis is one of the fastest ways to do caching in Laravel (and plain PHP too). Let’s break it down with easy examples.


πŸ”₯ 1. What is Redis?

  • An in-memory data store (everything is in RAM β†’ super fast ⚑).
  • Supports strings, lists, sets, hashes.
  • Used for caching, sessions, queues, pub/sub messaging.

🐘 2. Redis in Plain PHP

To use Redis in PHP, you install the phpredis extension or use Predis (PHP client).

Example (Predis):

require 'vendor/autoload.php';

$redis = new Predis\Client();

// Store in cache
$redis->setex("name", 60, "Ahmed"); // store for 60 sec

// Get from cache
echo $redis->get("name"); // Ahmed

// Delete
$redis->del("name");
Enter fullscreen mode Exit fullscreen mode

βœ… Works just like a key-value store.
βœ… But Laravel makes it even easier.


🎯 3. Redis in Laravel

πŸ”Ή Step 1: Install Redis

Make sure Redis is installed on your system and running:

redis-server
Enter fullscreen mode Exit fullscreen mode

Install PHP extension (if needed):

composer require predis/predis
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Step 2: Configure in .env

CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Step 3: Use Redis via Cache Facade

use Illuminate\Support\Facades\Cache;

// Store data
Cache::put('username', 'Ahmed', 60); // 60 sec

// Get data
echo Cache::get('username'); // Ahmed

// Remember (common use case)
$users = Cache::remember('users', 300, function () {
    return DB::table('users')->get();
});

// Forget
Cache::forget('username');
Enter fullscreen mode Exit fullscreen mode

βœ… Now instead of storing in files, Laravel stores in Redis memory.


πŸ“Š 4. Example: Cache Heavy Query with Redis

Route::get('/top-users', function () {
    $users = Cache::remember('top_users', 600, function () {
        return DB::table('users')
            ->orderBy('points', 'desc')
            ->limit(10)
            ->get();
    });

    return $users;
});
Enter fullscreen mode Exit fullscreen mode

➑️ First call β†’ hits DB, stores in Redis.
➑️ Next calls (10 min) β†’ served instantly from Redis.


πŸ”” 5. Example: Cache API Response with Redis

public function getWeather()
{
    return Cache::remember('weather_london', 900, function () {
        return Http::get('https://api.weatherapi.com/v1/current.json?key=API_KEY&q=London')
            ->json();
    });
}
Enter fullscreen mode Exit fullscreen mode

βœ… The API response is cached in Redis for 15 min.
βœ… No need to re-hit the external API.


πŸ› οΈ 6. Using Redis Facade Directly (Low-level)

use Illuminate\Support\Facades\Redis;

// Store
Redis::set('site_name', 'My Laravel App');

// Get
echo Redis::get('site_name');

// Increment counter
Redis::incr('visits');

// Lists
Redis::rpush('queue', 'task1');
Redis::rpush('queue', 'task2');
echo Redis::lpop('queue'); // task1
Enter fullscreen mode Exit fullscreen mode

βœ… In Summary

  • Plain PHP β†’ use Predis or phpredis.
  • Laravel β†’ just set CACHE_DRIVER=redis and use Cache or Redis facade.
  • Best for:

    • Heavy DB queries
    • API results
    • Session & authentication data
    • Queues

Top comments (0)