Using Laravel cache to store data in a cache, get the cache and then forget the data cache.
Laravel makes caching extremely easy and should be implemented if you are seeing the existence of sluggishness.
By using cache you can rapidly speed up your application and save on resources by not continuously doing database queries or calculations on the backend.
There are two main ways to store data into the cache, the first being put:
$users = Users::all();
Cache::put('all_users', $users); Here the Users data gets stored as the all_users key in the cache. You can also pass an extra parameter for the expiry time in minutes for the cache.
The next method is with using remember:
$users = Cache::remember('all_users', 60, function () {
return Users::all();
}); Remember is a retrieve BUT also store if not exists function. So if the all_users cache didn’t exist or it was expired (60 minutes / 1 hour set above) it would refresh it with the Users::all() data.
Using add means the cache will only be stored if that key is not already present in the cache.
Cache::add('all_users', $users); If using the file cache driver the cache files will be stored at storage/framework/cache.
Fetching items from Laravel cache can be done with get you just need to define its cache key:
$users = Cache::get('all_users'); You can check if the cache key exists, else get() will return null
if (Cache::has('all_users')) {
//Has cache
} else {
//No cache found
}
As shown above, the remember() function is also used to fetch cache however it will only return the cache if it exists.
Alternatively, you can get the cache data and then delete the cache in one command with pull
$users = Cache::pull('all_users');
Destroying or wiping an item from the cache is done with forget
Cache::forget('all_users'); If you ever wanted to clear the whole cache:
Cache::flush();
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…