Laravel Caching - Explained Simply
Tags: learning, laravel, development, caching
Published: 2024-07-06 17:47:54

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:

```php
$weatherData = getWeatherFromService();

Cache::put('current_weather', $weatherData, 60);
```
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:
```php
$weatherData = Cache::get('current_weather');
```

To check if the data is still there:

```php
if (Cache::has('current_weather')) {
    // It's there!
}
```

### Deleting Data from the Cache

To refresh weather data, remove old info:
```php
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:
```php
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();
});
```
- Use Model events to setup cache automation, to keep cache data up to date. Example:
```php
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();
        });
    }
}

```



## 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](https://twitter.com/laravelbackpack) - 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](https://backpackforlaravel.com/articles/tips-and-tricks/laravel-advanced-top-5-scheduler-functions-you-might-not-know-about). Keep exploring, and keep coding with ease using Laravel. Until next time, happy caching! 🚀