If the user’s already viewed (and downloaded) the image once, you can instruct their browser to just use the image in their local cache instead of requesting it from your server again.
Laravel has a built-in middleware for adding HTTP cache headers called cache.headers that you can use like this:
class PagesController extends Controller
{
public function __construct()
{
// Add ETag header to image responses
$this->middleware('cache.headers:etag')->only('image');
}
}
On a side-note, I’d ask why the method for fetching an image is in a pages controller. You‘re fetching an image. Why not move it to a ImageController@show method?
You can use options like etag and last_modified to set the corresponding HTTP headers.
I used cache.headers:etag a lot in an API project I recently worked on so that an ETag was added to each outgoing request. The user’s browser will record this ETag against the URL so that, if the URL was requested again, it would send the ETag and the server would reply with whether the content has changed or not. If not, it instructs the browser to just re-use the response it has in the cache, cutting out transferring the same data over the wire unnecessarily.