Skip to content
Nav

Query cache

composer require langsys/laravel-request-query-cache
Packagist version Monthly downloads License PHP 8.2+ Laravel 10 / 11 / 12
// Eloquent collection — caches ->get()
$locales = Locale::query()->getCached();
// Single model — caches ->first()
$invitation = UserInvitation::where('activation_token', $token)
->where('user_id', null)
->firstCached();

If the same query (identical SQL and bindings) runs again during the same request, it returns the stored result without touching the database.

$a = User::where('id', 1)->firstCached(); // hits the DB
$b = User::where('id', 1)->firstCached(); // served from cache, no DB hit
// $a === $b

Different queries are cached independently — bindings are part of the cache key, so where('id', 1) and where('id', 2) never collide.

  • A RequestQueryCache singleton holds an in-memory array keyed by md5(sql + serialized bindings).
  • getCached() wraps ->get(); firstCached() wraps ->first() (and prefixes its key with first: so the two never collide on the same query).
  • The store is flushed on app.terminating (covers PHP-FPM) and on Octane’s RequestReceived event when running under Laravel Octane, guaranteeing every request starts with an empty store.
Feedback