Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

whatthef's avatar

How can I cache specific urls?

I have an image url defined in web.php as

Route::get('/images/{path}/{number?}', 'PagesController@image')->name('images');

But since the images aren't public i have to send a file by putting

return response()->file($image);

Can I use cache for this kind of responses? If so how?

0 likes
3 replies
martinbean's avatar
Level 80

@whatthef You can use HTTP caching.

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?

1 like
whatthef's avatar

@martinbean Thank you where can I read more about this? And I thought this kind of thing is handled only by htaccess.

martinbean's avatar

@whatthef It’s not really documented, but you can read its source code here: https://github.com/laravel/framework/blob/de5f6a7ac9be7674820d24c1d5e9ababcaf00c3e/src/Illuminate/Http/Middleware/SetCacheHeaders.php

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.

Please or to participate in this conversation.