Monday 1 August 2016

Laravel cache interview questions and answers


Question: How to Store an value in cache?
$expiresAt = Carbon::now()->addMinutes(10);
Cache::put('name', 'My Name is Anurag', $expiresAt); //store for 20 mins



Question: How to Check an value stored in cache?
if (Cache::has('name'))
{
    
}



Question: How to Get an value stored in cache?
if (Cache::has('name'))
{
    $name = Cache::get('name');//My Name is Anurag
    
}



Question: How to Get an value from cache, If Not set get Default?
    $name = Cache::get('name2','unknown');//Return "unknown"



Question: How to Store an value in cache Permanently?
Cache::forever('name', 'My Name is Anurag'); //store Permanently



Question: Get value from cache, If not then set a default value?
$expiresAt = Carbon::now()->addMinutes(10);
$value = Cache::remember('users', $expiresAt, function(){
    return DB::table('users')->get();
});



Question: Get value from cache, If not then Delete?
$value = Cache::pull('name');



Question: Remove an Item from cache?
Cache::forget('name');



Question: Store an Integer value in cache?
Cache::put('sr', 10);



Question: Increase the Integer value in cache?
Cache::increment('sr');//change from 10 to 11



Question: Decrease the Integer value in cache?
Cache::decrement('sr');//change from 11 to 10



Question: Store an value in cache with tag?
Cache::tags('Tag1','Tag2')->put('name', 'My Name is Anurag', $minutes);