Laravel supports various cache drivers, which can be set in .env
:
CACHE_DRIVER=file
Use the cache()
helper or the Cache
facade to store data.
Example: Storing Data in Cache
use Illuminate\Support\Facades\Cache;
Cache::put('key', 'value', 600); // Stores 'value' for 10 minutes (600 seconds)
Use the get()
method to retrieve stored data.
Example: Retrieving Data from Cache
$value = Cache::get('key');
echo $value;
Before fetching, check if a key exists.
if (Cache::has('key')) {
echo Cache::get('key');
} else {
echo "No data found";
}
Use remember()
to store and fetch data if the key doesn’t exist.
$data = Cache::remember('users', 600, function () {
return DB::table('users')->get();
});
To clear a specific cache key:
Cache::forget('key');
If using Redis, install the Redis package:
composer require predis/predis
Use route caching to optimize performance:
php artisan route:cache
Laravel caching speeds up applications by reducing database queries and expensive computations. By leveraging different cache drivers, developers can optimize performance efficiently.
@asadmukhtar