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 rememberForever
method, and then we don't need to pass any time parameters.
app/Http/Controllers/Api/CategoryController.php:
class CategoryController extends Controller{ public function index() { abort_if(! auth()->user()->tokenCan('categories-list'), 403); return CategoryResource::collection(Cache::rememberForever('categories', function () { return Category::all(); })); } // ...}
Next, we must clear the cache after the category is created. We will use Eloquent Observer to do it.
php artisan make:observer CategoryObserver --model=Category
In this example, we will use the created
method inside Observer.
app/Observers/CategoryObserver:
use App\Models\Category;use Illuminate\Support\Facades\Cache; class CategoryObserver{ public function created(Category $category): void { Cache::forget('categories'); } // ...}
Now, when a new category is created, the categories
cache will be cleared, and after the next visit to the /categories
endpoint, all the results from the database will be re-added to the categories
cache key.