Skip to content
Advertisement

Laravel: how to cache route for 5 minutes?

I want to cache one route in Laravel project and clear it for every 5 minutes.

I searched a bunch of articles but only found artisan route:cache command and I have no idea if it possible to configure caching time.

So, this is my routes routes/web.php:

$router->group(['middleware' => ['api','cors']], function () use ($router) {
    $router->get('game', ['uses' => 'GameController@checkGameStatus']);
    $router->get('promo', ['uses' => 'PromoController@sendPromoCode']);
    $router->get('get_leaders', ['uses' => 'GameController@getLeaders']); // <-- cache this for 5m
});

And every time when user loads rating page the getLeaders() function initiates DB request to get and calculate all user results. Therefore I want to reduce DB load and make it calculating all results once in 5 minutes. The rest of the time get_leaders route should send back just cached json output.

How to set such configuration? Is it possible to do just with Laravel (artisan) or should I change .htaccess file (I am using apache)?

Advertisement

Answer

This is a pretty simple to solve problem actually. In your function getLeaders(), you’ll need to modify the code:

public function getLeaders(){
  $leadersCache = Cache::get("leaders", null);
  if($leadersCache){
    return response()->json(["leaders", $leadersCache], 200);
  }

  $leaders = Leader::where(...)->get();
  Cache::put("leaders", $leaders, 5);

  return response(["leaders", $leaders], 200);
}

So, what this does, is first, check if "leaders" exists in the cache. If it does, it will simply return that. If it doesn’t (which will be the case when this route is first called), then it will do the calculations, and using Cache::put(), store it in the cache, then return. For the next 5 minutes, anytime this route is hit, it will return the cached result, until the process is started over again.

Note the above is pseudo-code, as your Controller wasn’t shown, but the approach can be easily adapted to existing code. Also, you may need to include use Cache; at the top of your Controller, or reference Cache via Cache::{method}

Everything about the cache can be found in the documentation: https://laravel.com/docs/5.7/cache

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement