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