Introduction
Caching stores data so your app can get it quickly without doing the same work again. This makes your app respond faster.
Jump into concepts and practice - no test required
Caching stores data so your app can get it quickly without doing the same work again. This makes your app respond faster.
<?php use Illuminate\Support\Facades\Cache; // Store data in cache Cache::put('key', 'value', $seconds); // Get data from cache $value = Cache::get('key', 'default'); // Check if cache has key if (Cache::has('key')) { // do something } // Remove data from cache Cache::forget('key');
Use Cache::put() to save data with a time limit.
Use Cache::get() to retrieve data; provide a default if key is missing.
<?php Cache::put('user_1', 'John Doe', 3600);
<?php $name = Cache::get('user_1', 'Guest');
<?php if (Cache::has('settings')) { $settings = Cache::get('settings'); }
This example shows how caching avoids waiting 2 seconds every time. The first time it waits, then stores data. Next times it gets data instantly from cache.
<?php use Illuminate\Support\Facades\Cache; // Simulate fetching data from a slow source function getSlowData() { sleep(2); // wait 2 seconds return 'Fresh Data'; } // Try to get data from cache $data = Cache::get('slow_data'); if (!$data) { $data = getSlowData(); Cache::put('slow_data', $data, 60); // cache for 60 seconds } echo $data;
Caching helps reduce work your app repeats, saving time.
Remember to set an expiration time so data stays fresh.
Use cache wisely for data that does not change often.
Caching stores data to speed up future requests.
It reduces waiting by reusing saved results.
Laravel makes caching easy with simple methods.
if (Cache::has('users')) {
$users = Cache::get('users');
} else {
$users = User::all();
Cache::put('users', $users, 5);
}
echo count($users);$users = User::all()->toArray();
Cache::put('users', $users, 10);
$cachedUsers = Cache::get('users');
echo $cachedUsers->count();