0
0
Laravelframework~5 mins

Cache configuration in Laravel

Choose your learning style9 modes available
Introduction

Cache configuration helps your Laravel app store data temporarily to make it faster. It saves time by reusing data instead of creating it again.

When you want to speed up loading of pages by saving database query results.
When you need to store user session data quickly and efficiently.
When you want to reduce repeated API calls by caching responses.
When you want to improve performance of frequently accessed data.
When you want to control how long cached data stays before refreshing.
Syntax
Laravel
return [
    'default' => env('CACHE_DRIVER', 'file'),
    'stores' => [
        'file' => [
            'driver' => 'file',
            'path' => storage_path('framework/cache/data'),
        ],
        'redis' => [
            'driver' => 'redis',
            'connection' => 'cache',
        ],
        // other cache stores...
    ],
    'prefix' => env('CACHE_PREFIX', 'laravel_cache'),
];

The default key sets which cache driver Laravel uses by default.

You can configure multiple cache stores like file, redis, database, etc., inside the stores array.

Examples
This sets the cache driver to file and changes the cache prefix to 'myapp_cache' in your .env file.
Laravel
CACHE_DRIVER=file
CACHE_PREFIX=myapp_cache
This configures Laravel to use Redis as the default cache store.
Laravel
'default' => env('CACHE_DRIVER', 'redis'),

'stores' => [
    'redis' => [
        'driver' => 'redis',
        'connection' => 'cache',
    ],
],
This example shows how to configure database caching using a table named 'cache'.
Laravel
'stores' => [
    'database' => [
        'driver' => 'database',
        'table' => 'cache',
        'connection' => null,
    ],
],
Sample Program

This example stores a greeting message in the cache for 10 minutes and then retrieves it. If the cache is empty, it shows a default message.

Laravel
<?php

use Illuminate\Support\Facades\Cache;

// Store a value in cache for 10 minutes
Cache::put('greeting', 'Hello, friend!', 600);

// Retrieve the cached value
$value = Cache::get('greeting', 'Default greeting');

// Output the cached value
echo $value;
OutputSuccess
Important Notes

Remember to clear cache after changing configuration using php artisan cache:clear.

Use environment variables to easily switch cache drivers between local and production.

File cache stores data in storage folder; Redis cache requires Redis server setup.

Summary

Cache configuration controls how Laravel stores temporary data to speed up your app.

You can choose different cache drivers like file, Redis, or database.

Set cache duration and prefix to organize cached data safely.