Laravel Advanced: Caching - Explained Simply

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...

Karan Datwani
Karan Datwani
Share:

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.

How Does Caching Work in Laravel?

Laravel has a built-in storage called cache. It helps you store data and quickly get it later.

Storing Data in the Cache

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).

Retrieving and Checking Data

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!
}

Deleting Data from the Cache

To refresh weather data, remove old info:

Cache::forget('current_weather');

Cool Things You Can Do with Caching

  • For a busy blog or for an online shop, cache posts & products to boost speed:
// 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);
    }    
}
  • Cache frequently requested API responses to reduce load and improve response time:
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;
}
  • Cache expensive queries used to generate dashboard metrics:
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;
}
  • Cache frequently accessed data like settings or configurations, product categories or navigation menus.
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;
}
  • Automate Cache Invalidation via model events. 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');
    });
		
}

Wrapping Up

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! 🚀

Want to receive more articles like this?

Subscribe to our "Article Digest". We'll send you a list of the new articles, every week, month or quarter - your choice.

Reactions & Comments

What do you think about this?

Latest Articles

Wondering what our community has been up to?