Remember your Query results using only one method. Yes, only one.
User::latest()->where('name', 'Joe')->remember()->get();
- PHP 7.2 or latest
- Laravel 5.8|6.x
- A working brain
You can install the package via composer:
composer require darkghosthunter/rememberable-query
Just use the remember()
method to remember a Query result. That's it.
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Auth\User;
$query = DB::table('users')->remember()->where('name', 'Joe')->first();
$eloquent = User::where('name', 'Joe')->remember()->first();
The next time you call the same query, the result will be retrieved from the cache instead of running the SQL statement in the database.
If the result is
null
orfalse
, it won't be remembered, which mimics the Cache behaviour on these values.
By default, queries are remembered by 60 seconds, but you're free to use any length, Datetime, DateInterval or Carbon instance.
User::where('name', 'Joe')->remember(today()->addHour())->first();
By default, the cache key is an MD5 hash of the SQL query and bindings, which avoids any collision with other queries. You can use any string, but is recommended to append query|{key}
to avoid conflicts with other cache keys in your application.
User::where('name', 'Joe')->remember(30, 'query|find_joe')->first();
In some scenarios, using the default cache of your application may be detrimental compared to the database performance. You can use any other Cache by telling the Service Container to pass it to the RememberableQuery
class (preferably) in your AppServiceProvider
.
public function boot()
{
$this->app
->when(\DarkGhostHunter\RememberableQuery\RememberableQuery::class)
->needs(\Illuminate\Contracts\Cache\Repository::class)
->give(function () {
return cache()->store('redis');
});
// ...
}
There are two things you should be warned about.
Altering the Builder methods order may change the automatic cache key generation. Even if they are practically the same, the order of statements makes them different. For example:
<?php
DB::table('users')->remember()->whereName('Joe')->whereAge(20)->first();
// "query|fecc2c1bb6396e485d94eede60532937"
DB::table('users')->remember()->whereAge(20)->whereName('Joe')->first();
// "query|3ac5eba7cd0ef6151481bdfe46f6c22f"
If you plan to remember the same query on different parts of your application, it's recommended to set manually the same Cache Key to ensure hitting the cached results.
The nature of remembering a Query is to cache the result automatically.
Caching the result for UPDATE
, DELETE
and INSERT
operations will cache the result and subsequents operations won't be executed, returning unexpected results.
Don't use remember()
on anything that is not a SELECT
statement.
The MIT License (MIT). Please see License File for more information.