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.
Cache drivers (file, Redis, Memcached) in 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.
Cache::driver('file')->put('username', 'Alice', now()->addSeconds(3600)); $username = Cache::driver('file')->get('username');
Cache::driver('redis')->put('count', 10, now()->addSeconds(600)); $count = Cache::driver('redis')->get('count');
Cache::driver('memcached')->put('settings', ['theme' => 'dark'], now()->addSeconds(1800)); $settings = Cache::driver('memcached')->get('settings');
This example stores a greeting message in the file cache for 5 minutes and then retrieves and prints it.
<?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;
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.
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.