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

mrkarma4ya's avatar

Caching API response and remembering position when route changes

Hi,

Lets say I have a posts route and a posts/:id route. When user visits posts, I load all posts (paginated) in the mounted hook and display them. When user clicks on one post, they are sent to posts/:id route. But when they hit back, the posts are loaded all over again and user has to scroll all the way down to the last post they opened.

How can I make it so that the API response is cached and scroll state is remembered, so when they click back button, they can right where they left?

0 likes
1 reply
BenSeDev's avatar

It depends on how you're fetching the paginated responses now. But you could wrap a caching layer around your current DB implementation.

Some pseudo code to clarify what I mean.

So imagine this is your current class where you fetch the paginated results:


class PostsDb
{
	public function get(...some params...) {
				// Pagination Magic happens here
		}
}

You could wrap a caching layer around it:

use Illuminate\Cache\Repository

class PostsCaching
{
	public function __construct(private PostsDb $posts, private Repository $cache)

	public function get(...some params...) {
		$cacheKey = 'A unique key, composed out of certain ids...';

		$posts = $this->cache->get($cacheKey);
        if ($posts) {
            return $posts;
        }

        $user = $this->repository->get(... some params...);

        if ($posts === null) {
            $this->cache->forget($cacheKey);
            return null;
        }

        $this->cache->forever($cacheKey, $posts);

        return $posts;
	}
}

Of course to do it right you would be best it implement a repository interface, reference that instead if the implementations. But you get the gist of what I mean? If not, feel free to shout out.

Please or to participate in this conversation.