Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add browser cache in Laravel 5?

I wish to add browser caching to my Laravel application.

I have used Elixir versioning tool like so: https://laravel.com/docs/5.2/elixir#versioning-and-cache-busting

However, according to Google PageSpeed Insights, the files is still not caching and I instead got this message:

Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network.

I think this may be because I need to manually add cache headers?

like image 247
Yahya Uddin Avatar asked Apr 25 '16 01:04

Yahya Uddin


People also ask

How do I enable browser caching in Laravel?

To enable Laravel caching services, first use the Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository, as they provide access to the Laravel caching services. The Factory contract gives access to all the cache drivers of your application.

Does Laravel have caching?

Laravel supports popular caching backends like Memcached, Redis, DynamoDB, and relational databases out of the box. In addition, a file based cache driver is available, while array and "null" cache drivers provide convenient cache backends for your automated tests.

Does Laravel view cache?

When a request is executed that renders a view, Laravel will compile the view if a pre-compiled view does not already exist (or if the view has been modified more recently than the compiled view). View caching pre-compiles all of the views utilized by your application.

Where is Laravel cache stored?

Laravel provides a unified API for various caching systems. The cache configuration is located at app/config/cache. php . In this file you may specify which cache driver you would like used by default throughout your application.


1 Answers

Yes you need to set Cache-Control and Expires in HTTP header for static resources, so that this Google PageSpeed message will not show up.

Since you're already using Elixir versioning tool, you can safely set Expires of JS/CSS files to 1 week.

The way to do it depends on what web server you are using.

If you are using Apache, you may put the following code in .htaccess or the config file of your virtual website.

<FilesMatch "\.(js|css)$">
  ExpiresActive On
  ExpiresDefault "access plus 1 weeks"
</FilesMatch>

Be sure to enable the mod_expires Apache module!

With the same syntax, you can set up cache rules for .html, .jpg, .png files and so on, to speed up page loading.

If you are using nginx, there are similar ways to solve this problem, you may follow this tutorial

like image 98
Kevin Avatar answered Sep 28 '22 08:09

Kevin