0
0
Laravelframework~5 mins

Cache drivers (file, Redis, Memcached) in Laravel

Choose your learning style9 modes available
Introduction

Cache drivers help store data temporarily to make your app faster. They save information so your app doesn't have to do the same work again and again.

When you want to speed up loading pages by saving data that doesn't change often.
When you want to reduce database queries by storing query results temporarily.
When you want to share cached data between multiple servers using Redis or Memcached.
When you want to store session data quickly and efficiently.
When you want to cache API responses to avoid repeated calls.
Syntax
Laravel
Cache::driver('driver_name')->put('key', 'value', now()->addSeconds($seconds));
Cache::driver('driver_name')->get('key');

Replace 'driver_name' with 'file', 'redis', or 'memcached' depending on your setup.

The put method saves data with a key and expiration time as a DateTime or DateInterval instance.

Examples
This saves 'Alice' under 'username' in a file cache for 1 hour, then retrieves it.
Laravel
Cache::driver('file')->put('username', 'Alice', now()->addSeconds(3600));
$username = Cache::driver('file')->get('username');
This stores the number 10 in Redis cache for 10 minutes and then gets it back.
Laravel
Cache::driver('redis')->put('count', 10, now()->addSeconds(600));
$count = Cache::driver('redis')->get('count');
This caches an array of settings in Memcached for 30 minutes and retrieves it.
Laravel
Cache::driver('memcached')->put('settings', ['theme' => 'dark'], now()->addSeconds(1800));
$settings = Cache::driver('memcached')->get('settings');
Sample Program

This example stores a greeting message in the file cache for 5 minutes and then retrieves and prints it.

Laravel
<?php
use Illuminate\Support\Facades\Cache;

// Store a value in file cache for 5 minutes
Cache::driver('file')->put('greeting', 'Hello, Laravel!', now()->addSeconds(300));

// Retrieve the cached value
$message = Cache::driver('file')->get('greeting');

// Output the message
echo $message;
OutputSuccess
Important Notes

File cache stores data on your server's disk and is simple to use but slower than Redis or Memcached.

Redis and Memcached are in-memory caches, so they are faster and good for shared or large-scale apps.

Make sure Redis or Memcached servers are installed and running before using their drivers.

Summary

Cache drivers let you save and get data quickly to speed up your app.

Use 'file' for simple local caching, 'redis' or 'memcached' for faster, shared caching.

Always set how long cached data should live to keep it fresh.