Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CRUGG's avatar
Level 1

Cache External Rest API in Laravel

Let's say I want to obtain data from an External REST API through this. How would I cache this Data to e.g. only have max. 1 Request per Minute to the external API Endpoint with Laravel's Caching? Is there anything I can enable or any packages I can use to achieve this? Or what would I have to do?

0 likes
5 replies
Sinnbeck's avatar

Something like this. Put this in a class method somewhere (perhaps an action if you are using that pattern)

Use whatever caching you wish here (redis, file etc.). I use redis in the example. Also replace http call with whatever you need

$data = Cache::store('redis')->remember('someclevername', 60, function () {
            return Http::get('http://test.com/users', [
                 'page' => 1,
          ]);
        });
1 like
CRUGG's avatar
Level 1

Hm yeah that would work I just thought there's maybe a direct way to cache Responses (so when calling the Endpoint, I get the cached version) Would this work?

$data = Cache::store('redis')->get('myEndpoint');
if(isset($data)) {
	return $data;
} else {
	$response = Http:get('https://example.tld/api/endpoint'):
	Cache::store('redis')->put('myEndpoint', $response, 60);
	return $response;
}

I'm definitely not the best programmer. If anyone has some Improvements to my Code, I'd be happy to hear them.

1 like
Sinnbeck's avatar

To my knowledge, guzzle does not support caching. Also I would personally use laravel cache to make sure that I have full control. My own example would be exactly how I would do it

CRUGG's avatar
Level 1

From how I understand it, your Code, runs the Query and caches that, however, I have no Idea how I'd then get the Information. Because I basically needs a function that, if the Request is cached, returns that. And if not, requests, caches and then returns that

martinbean's avatar

@crugg You can wrap your requests in a repository that has a caching layer. You would then interact with this repository class.

class FooRepository
{
    public function fooRequest()
    {
        $key = 'cache.key.here';
        $ttl = 60; // 60 seconds / 1 minute

        return Cache::remember($someKey, $ttl, function () {
            return Http::get('http://example.com/api');
        });
    }
}
protected $foos;

public function __construct(FooRepository $foos)
{
    $this->foo = $foos;
}

public function someClassMethod()
{
    $response = $this->foos->fooRequest(); // will cache
}
1 like

Please or to participate in this conversation.