DEV Community

Cover image for Laravel Caching - Explained Simply
Karan Datwani
Karan Datwani

Posted on • Originally published at backpackforlaravel.com

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

Top comments (0)