Caching is like keeping your favorite toy right on top of your toy box, so you can grab it quickly whenever you want to play. Similarly...
Caching is like keeping your favorite toy right on top of your toy box, so you can grab it quickly whenever you want to play.
Similarly, cache in Laravel stores data so your website can show it quickly without searching or querying all over again. Just like finding your toy faster, caching helps websites load faster.
Laravel has a built-in storage called cache
. It helps you store data and quickly get it later.
For example - weather data. Weather won't change on every request, so why make a DB or API call every time? It would be way more efficient to keep the info handy in the cache:
use Illuminate\Support\Facades\Cache;
$weatherData = getWeatherFromService();
Cache::put('current_weather', $weatherData, now()->addMinutes(60));
Here, current_weather
is the cache key, $weatherData
is the info, and an expiration time(DateTime instance or an integer in seconds).
To get weather data from the cache:
$weatherData = Cache::get('current_weather');
To check if the data is still there:
if (Cache::has('current_weather')) {
// It's there!
}
To refresh weather data, remove old info:
Cache::forget('current_weather');
// Fetching paginated blog posts/products with caching:
public function index()
{
$page = request()->get('page', 1);
$cacheKey = 'blog_page_' . $page;// unique key for each posts page
$posts = Cache::remember($cacheKey, 3600, function () {
return Post::paginate(10);
});
$cacheKey = 'products_page_' . $page; // unique key for each products page
$products = Cache::remember($cacheKey, 3600, function () {
return Product::paginate(10);
});
}
// Remember to remove cache when a new product is created, updated or destroyed.
public function store(Request $request){
$product = Product::create($request->all());
// Clear the cache for all pages
$totalPages = ceil(Product::count() / 10);
for ($i = 1; $i <= $totalPages; $i++) {
Cache::forget('products_page_' . $i);
}
}
public function getWeatherData($city)
{
$cacheKey = 'weather_' . $city;
$weatherData = Cache::remember($cacheKey, 3600, function () use ($city) {
$response = Http::get('https://api.weatherapi.com/v1/current.json',['key' => 'your_api_key', 'q' => $city]);
return $response->json();
});
return $weatherData;
}
public function getDashboardMetrics()
{
$cacheKey = 'dashboard_metrics';
$metrics = Cache::remember($cacheKey, 3600, function () {
return [
$monthlySales = Order::selectRaw('MONTH(created_at) as month, COUNT(*) as total_orders, SUM(total) as total_revenue')->whereYear('created_at', date('Y'))->groupBy(DB::raw('MONTH(created_at)'))->orderBy('month')->get(),
$userRegistrations = User::selectRaw('MONTH(created_at) as month, COUNT(*) as total_registrations')->whereYear('created_at', date('Y'))->groupBy(DB::raw('MONTH(created_at)'))->orderBy('month')->get(),
$topProducts = Product::select('products.id', 'products.name')->join('order_product', 'order_product.product_id', '=', 'products.id')->join('orders', 'orders.id', '=', 'order_product.order_id')->selectRaw('COUNT(order_product.product_id) as total_sold, SUM(order_product.price * order_product.quantity) as total_revenue')->groupBy('products.id', 'products.name')->orderByDesc('total_sold')->take(5)->get(),
$averageOrderValue = Order::selectRaw('MONTH(created_at) as month, AVG(total) as avg_order_value')->whereYear('created_at', date('Y'))->groupBy(DB::raw('MONTH(created_at)'))->orderBy('month')->get(),
// ...
];
});
return $metrics;
}
public function getSetting($key)
{
$cacheKey = 'setting_' . $key;
$setting = Cache::rememberForever($cacheKey, function () use ($key) {
return Setting::where('key', $key)->first();
});
return $setting ? $setting->value : null;
}
public function getCategories()
{
$cacheKey = 'categories';
$categories = Cache::remember($cacheKey, 86400, function () {
return Category::all();
});
return $categories;
}
EventServiceProvider.php
can be a good place to register them.public function boot()
{
Order::created(function () {
Cache::forget('dashboard_metrics');
});
User::created(function () {
Cache::forget('dashboard_metrics');
});
Product::updated(function () {
Cache::forget('dashboard_metrics');
});
}
Caching in Laravel makes websites faster by storing data for quick access. Start using caching to speed up your Laravel app and make users happy!
All of the above have been previously shared on our Twitter, one by one. If you're on Twitter, follow us - you'll ❤️ it. You can also check the first article of the series, which is on the Top 5 Scheduler Functions you might not know about. Keep exploring, and keep coding with ease using Laravel. Until next time, happy caching! 🚀
Subscribe to our "Article Digest". We'll send you a list of the new articles, every week, month or quarter - your choice.
What do you think about this?
Wondering what our community has been up to?