Custom driver for image cache in Laravel Valet

Now and then you will need a way to serve resized images. I wanted a way to create this images and cache the result dynamically.

A smart way to caching without booting up Laravel for each request is to cache the files directly to disk and let Nginx via try_files serve the response if the image is available, there is no reason to have to boot up a full PHP app to serve a single image.

In Nginx land it would look like this:

location / {
    try_files $uri $uri/ /image-cache/$uri /index.php?$query_string;
}

The recommended way of having site specific configuration in Laravel Valet seems to be to write a custom driver. Turns out writing the equivalent Laravel Valet drivers of try_files is simple, even more, comfortable if you know PHP.


public function isStaticFile($sitePath, $siteName, $uri)
{
    // Does the request URI beginns with '/images/
    if (strpos($uri, $this->cacheUri) === 0) {
        $cacheUri = str_replace($this->cacheUri, $this->cachePath, $uri);
        
        // cached file does exist, show it
        if (file_exists($staticFilePath = $sitePath.'/public/'.$cacheUri)) {
            return $staticFilePath;
        } 
        
        return false;
    }
    
    // Is there an another static file?
    if (file_exists($staticFilePath = $sitePath.'/public/'.$uri)) {
        return $staticFilePath;
    }
    
    return false;
}

Full code

https://gist.github.com/jannejava/671f8e7c414906b5fef67c1ad61a5e4e