Courses

How to Build Laravel 11 API From Scratch

Cache and Observers

Summary of this lesson:
- Implementing API response caching
- Using Cache::rememberForever for permanent caching
- Auto-clearing cache with Observers

In this lesson, let's talk about caching. For example, categories will mostly stay the same or could not change for years or even ever. For such cases, we can introduce cache and not make any queries to the database.


Let's introduce a cache for 24 hours.

app/Http/Controllers/Api/CategoryController.php:

use Illuminate\Support\Facades\Cache;
 
class CategoryController extends Controller
{
public function index()
{
abort_if(! auth()->user()->tokenCan('categories-list'), 403);
 
return CategoryResource::collection(Cache::remember('categories', 60*60*24, function () {
return Category::all();
}));
}
 
// ...
}

For checking queries, I will be using the Laravel Telescope package.

We can see the query was executed after going to the /categories endpoint in the Telescope.

The query won't be executed for the next 24 hours.

But we can do even better in this case. We can cache forever and clear the cache automatically, instead of doing it manually when a new category is created.

First, the caching. Instead of remember, we use...

The full lesson is only for Premium Members.
Want to access all 23 lessons of this course? (58 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord