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;
β
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
π― 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
πΉ 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');
πΉ Remember Pattern
Very common in Laravel:
$users = Cache::remember('users', 60, function () {
return DB::table('users')->get();
});
β‘οΈ 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']);
Remove it:
Cache::forget('site_settings');
β‘ 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();
});
}
β
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
orrememberForever
instead of manually managing put/get. - Clear cache safely:
php artisan cache:clear
- For config caching:
php artisan config:cache
β 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");
β
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
Install PHP extension (if needed):
composer require predis/predis
πΉ Step 2: Configure in .env
CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
πΉ 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');
β 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;
});
β‘οΈ 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();
});
}
β
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
β In Summary
-
Plain PHP β use
Predis
orphpredis
. -
Laravel β just set
CACHE_DRIVER=redis
and useCache
orRedis
facade. -
Best for:
- Heavy DB queries
- API results
- Session & authentication data
- Queues
Top comments (0)