Laravel Headers and Caching in php Laravel Headers and Caching in php laravel laravel

Laravel Headers and Caching in php


An alternative method to this would be to check for the 'If-Modified-Since' request header as it will only be present if the browser already has the file.

If it is present, then you know the file is already created and can respond with a link to it, otherwise run your code above. Something like this...

// check if the client validating cache and if it is currentif ( isset( $headers['If-Modified-Since'] ) && ( strtotime( $headers['If-Modified-Since'] ) == filemtime( $image->get_full_path() ) ) ) {    // cache IS current, respond 304    header( 'Last-Modified: ' . $image->get_last_modified(), true, 304 );} else {    // not cached or client cache is older than server, respond 200 and output    header( 'Last-Modified: ' . $image->get_last_modified(), true, 200 );    header( 'Content-Length: ' . $image->get_filesize() );    header( 'Cache-Control: max-age=' . $image->get_expires() );    header( 'Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + $image->get_expires() ) );    header( 'Content-Type: image/jpeg');    print file_get_contents( $image->get_full_path() ); }


It appears that you are still telling Laravel to download the asset and serve the response as a download, you can provide a Cache-Control header, but it does not matter because you are re-generating this asset each time the image is loaded.

I ran into a similar problem myself and found the best way to serve the images was to inject a static function into my view something like ImageController:fetchImage($image).

The method then will then check a local folder to see if the file exists and then it will just return the location of the image, something like: /img/1332.jpg... If the file does not exist it will create the image, save it to the img folder and then return the location.

This avoids laravel from ever having to serve up a brand new (uncached) response as a download EACH time the image is requested and instead directs the browser to load resources that are already cached.

This worked in my case that is...

    if (App::environment('local'))    {       return 'http://placehold.it/150x150';    }    $target_file = 'img_cache/'. $release_id .'.jpg';    if (file_exists($target_file)) return '/'.$target_file;    else    {        $release = DB::(get release location on another server from db);        if(!$release)            return 'http://placehold.it/150x150';        $imageString = file_get_contents("http://pomed.promoonly.com/".$release[0]->image_src);        file_put_contents($target_file, $imageString);        return '/'.$target_file;    }