Logo

dev-resources.site

for different kinds of informations.

Laravel Caching - Explained Simply

Published at
7/6/2024
Categories
learning
laravel
development
caching
Author
karandatwani92
Author
14 person written this
karandatwani92
open
Laravel 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, 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 quickly.

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:

$weatherData = getWeatherFromService();

Cache::put('current_weather', $weatherData, 60);
Enter fullscreen mode Exit fullscreen mode

Here, current_weather is the cache key, $weatherData is the info, and 60 is the minutes to keep it.

Retrieving and Checking Data

To get weather data from the cache:

$weatherData = Cache::get('current_weather');
Enter fullscreen mode Exit fullscreen mode

To check if the data is still there:

if (Cache::has('current_weather')) {
    // It's there!
}
Enter fullscreen mode Exit fullscreen mode

Deleting Data from the Cache

To refresh weather data, remove old info:

Cache::forget('current_weather');
Enter fullscreen mode Exit fullscreen mode

Cool Things You Can Do with Caching

  • For a busy blog or for an online shop, cache posts & products to boost speed:
use Illuminate\Support\Facades\Cache;

$blogPosts = Cache::remember('blog_posts', 30, function () {
    return DB::table('posts')->get();
});

$productList = Cache::remember('product_list', 10, function () {
    return Product::all();
});
Enter fullscreen mode Exit fullscreen mode
  • Use Model events to setup cache automation, to keep cache data up to date. Example:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Post extends Model
{
    protected $fillable = ['title', 'content'];

    protected static function boot()
    {
        parent::boot();

        static::retrieved(function ($post) {
            Cache::remember("post_{$post->id}", 60, function () use ($post) {
                return $post;
            });
        });

        static::created(function ($post) {
            Cache::forget('all_posts');
            Cache::remember("post_{$post->id}", 60, function () use ($post) {
                return $post;
            });
        });

        static::updated(function ($post) {
            Cache::forget("post_{$post->id}");
            Cache::forget('all_posts');
            Cache::remember("post_{$post->id}", 60, function () use ($post) {
                return $post;
            });
        });

        static::deleted(function ($post) {
            Cache::forget("post_{$post->id}");
            Cache::forget('all_posts');
        });
    }

    public static function getAllPosts()
    {
        return Cache::remember('all_posts', 60, function () {
            return self::all();
        });
    }

    public static function searchPosts($query)
    {
        return Cache::remember("search_posts_{$query}", 60, function () use ($query) {
            return self::where('title', 'like', "%{$query}%")
                       ->orWhere('content', 'like', "%{$query}%")
                       ->get();
        });
    }
}

Enter fullscreen mode Exit fullscreen mode

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! ๐Ÿš€

caching Article's
30 articles in total
Favicon
How to Implement Caching in PHP and Which Caching Techniques Are Best for Performance?
Favicon
Understanding Memcached: A Powerful In-Memory Caching Solution by Abhay
Favicon
Caching with Redis for Backend in Apache Superset
Favicon
The Most Popular Database Caching Strategies Explained
Favicon
Melhorando o Desempenho da Sua Aplicaรงรฃo PHP com Lithe Cache
Favicon
Cache Strategies: A Complete Guide with Real-Life Examples ๐Ÿš€
Favicon
Caching โ€” An overview
Favicon
Bloom Filters
Favicon
HybridCache in ASP.NET Core - New Caching Library
Favicon
Advanced Data Caching Techniques for High-Performance Systems
Favicon
Redis: Understanding the Basics
Favicon
Implementing Caching Strategies for Improved Performance
Favicon
Improving the Performance of Your PHP Application with Lithe Cache
Favicon
Redis caching with Mongoose
Favicon
Building Scalable Web Applications: Techniques for Handling High Traffic
Favicon
๐Ÿš€Optimize Web Performance in the Cloud with Caching!๐Ÿš€
Favicon
Top 5 Next.js Caching Solutions for Next.js Apps (2024)
Favicon
Building a cache in Python
Favicon
Caching in .Net 8: Improving Application Performance
Favicon
Davide's Code and Architecture Notes - Cache Expiration vs Cache Eviction (and Eviction Policies)
Favicon
Conquering the Cache Calamity: My Journey to HNG Internship
Favicon
Next.js Caching Issues With Fetching Data
Favicon
MemoryCache in C#: A Practical Guide
Favicon
Caching & Memoization with state variables
Favicon
Laravel Caching - Explained Simply
Favicon
A way to cache responses in Grape API
Favicon
The Power of Caching and How to Implement It in Your Python Applications
Favicon
Caching
Favicon
Cost-Effective Image Management: Maximizing Efficiency Through Network Image Caching in Mobile Apps
Favicon
Top Redis Use Cases

Featured ones: