Optimising Laravel Deployments
This play book will walk you through some different configuration options for improving application performance.
Nginx Asset Caching
Section titled “Nginx Asset Caching”This step will assume we’re using Nginx to serve assets. Add the following to the Nginx config. This will add Cache-Control headers that will cache different build assets locally on client machines.
location ^~ /build/assets/ { add_header Cache-Control "public, max-age=31536000, immutable" always; access_log off; try_files $uri =404;}
location ~* \.(?:avif|gif|ico|jpe?g|png|svg|webp)$ { add_header Cache-Control "public, max-age=2592000" always; access_log off; try_files $uri =404;}The location of build assets may change, so adjust accordingly. These are usually minified chunks like /build/assets/shared-B7PI925R.js. We give these files 1 year cache time, since if they get updated, the hash string on the end of the filename will update and the client will always fetch the latest.
For images, the standard is to cache these for 30 days.
Opcache
Section titled “Opcache”PHP-FPM
Section titled “PHP-FPM”Caching Repository Methods
Section titled “Caching Repository Methods”This is mostly just a reminder to explore this if you haven’t already. The way we use repository pattern at Novatura is ideal for implementing caching. The repositories separate application concerns, make majority the database calls, and each method takes parameters that function well as cache keys.
To reduce the number of network calls, we can wrap the repository methods in Illuminate\Support\Facades\Cache::remember().
public function getUsers(string $search): array{ return Cache::remember( ['get-users', $search], now()->addHours(1), fn() => Users::where("name", "LIKE", "%" . $search . "%")->get()->toArray() );}Make sure that cache keys are flushed appropriately when the models they cache are updated elsewhere in the application. There may be many call sites, so proper design and planning is advised.