0
0
Laravelframework~5 mins

Why caching reduces response times in Laravel

Choose your learning style9 modes available
Introduction

Caching stores data so your app can get it quickly without doing the same work again. This makes your app respond faster.

When you want to show a list of popular products that doesn't change often.
When you need to speed up loading user profiles that are visited many times.
When your app fetches data from slow external services and you want to avoid waiting every time.
When you want to reduce the load on your database by reusing previous query results.
Syntax
Laravel
<?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.

Examples
Saves 'John Doe' under 'user_1' for 1 hour (3600 seconds).
Laravel
<?php
Cache::put('user_1', 'John Doe', 3600);
Gets 'user_1' from cache or returns 'Guest' if not found.
Laravel
<?php
$name = Cache::get('user_1', 'Guest');
Checks if 'settings' exist in cache before getting it.
Laravel
<?php
if (Cache::has('settings')) {
    $settings = Cache::get('settings');
}
Sample Program

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.

Laravel
<?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;
OutputSuccess
Important Notes

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.

Summary

Caching stores data to speed up future requests.

It reduces waiting by reusing saved results.

Laravel makes caching easy with simple methods.