Laravel Cache: Complete Guide and Explanation
Laravel Cache is an expressive, unified API for various caching backends, allowing you to temporarily store data for faster retrieval. This significantly reduces database load and improves application performance.
Basic Put and Get
To store an item in the cache, use the Cache::put method. You can retrieve it using the Cache::get method.
use Illuminate\Support\Facades\Cache;
// Storing data for 60 seconds
Cache::put('key', ‘value’, 60);
// Retrieving data
$value = Cache::get('key');
The Remember Method
The remember method checks the cache for an item. If it exists, it returns it. If not, it executes the closure, stores the result in the cache, and returns it.
$users = Cache::remember('users', 600, function () {
return DB::table('users')→get();
});
Cache TTL (Time To Live)
TTL specifies how long an item should remain in the cache. In Laravel, you can pass the number of seconds (or a DateTime instance) as the third argument to the put method.
Laravel supports various drivers like:
- File
- - Database
- - Redis / Memcached