Cache Larastan results in Github Actions


We previously shared how we sped up our CI pipeline by cleaning up unused Docker setup and build tasks. Today's tip shows how we used caching to make it even faster.

Typically, I had used Github Actions caching to cache the output from npm install and composer install. That way, if we're not changing dependencies, those pipeline steps could run much faster.

But looking at the output logs from our pipeline runner, we could see that Larastan was taking 40 - 50 seconds to run. When I run it locally, it goes much faster, and that's due to the Larastan (actually the PHPStan) results cache. It's able to use the cached results from previous runs to speed up new runs for only changed files.

This is slightly less obvious how to cache in a CI pipeline however. Unlike npm and composer, there isn't one lock file I can hash to know if something has changed, and the cache needs to be invalidated.

Here's what we ended up with:

Larastan caching in Github Actions

The tricky bit is that we use a set of multiple restore keys, and the fact that Github Actions checks them in a specific order with partial match support, so that we can always save the latest run in the cache, but also take advantage of the previous cached run.

And note that you must also configure PHPStan to place its cache in the .phpstan.cache location, and then exclude it in your .gitignore so it doesn't get committed to the repo accidentally.

Success! This shaved another 30 - 40 seconds off our pipeline, and now it's running a little over 3 minutes on average.

Here to help,


P.S. Ever feel stuck figuring out a bug or getting something to work? We can help!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.