How to store all records in laravel 5.3 Cache
In this tutorials, i am going to tell you how to work with cache in Laravel.
You can easily save database record in cache and easily you can get that record from cache in Laravel.
Cache is knows as persistence layer between database and application and it is used to improve website performance because sometime database query is going very slow due to lots of traffic at same time on website then retrieving data from cache is much quicker rather than from a database.
Memcached is know as very popular caching system which is used by many high trafficked websites.
Putting an item in the cacheWe can easily add or update value in cache by using put()
method and we pass 3 parameters in this method.
Cache::put('key', 'value', 30);
In 3rd parameters we pass expiration time in minutes.
Getting an item from the cacheWe can easily get item from cache and also we can check if cache has the key you are looking for.
- if( Cache::has( 'key' ) ) {
- return Cache::get( 'key' );
- }
We use remember()
to cache the database result while querying from database.
$users = User::remember(10)->get();
Sometime you want to retrieve data from cache but requested data does not exist in cache then store default data in cache.
- $allproducts = Cache::remember('allproducts',60, function() {
- return DB::table('products')->get();
- });
You can remove records from cache using forget
method.
Cache::forget('allproducts');
You can clear entire records from cache using flush
method.
Cache::flush();