How to Set Cache Control In Laravel?

6 minutes read

To set cache control in Laravel, you can use the Cache facade provided by the framework. The Cache facade allows you to interact with the cache system in Laravel and set cache control headers.


To set cache control in Laravel, you can use the cache() method on the Cache facade and pass in the key and value for the cache. You can also set the expiration time for the cached data by passing in a duration in minutes.


For example, if you want to cache a piece of data for 60 minutes, you can use the following code:

1
Cache::put('key', 'value', 60);


This will store the data with the key 'key' in the cache for 60 minutes. You can retrieve this data later by using the get() method on the Cache facade:

1
$value = Cache::get('key');


In addition to setting cache control at the application level, you can also set cache control headers in your routes or controller methods using the header() method. For example, to set the Cache-Control header to no-cache for a route, you can use the following code:

1
2
return response($content)
    ->header('Cache-Control', 'no-cache');


By setting cache control in Laravel, you can improve the performance of your application by caching frequently accessed data and controlling how that data is cached and served to users.

Best Laravel Cloud Hosting Providers of October 2024

1
DigitalOcean

Rating is 5 out of 5

DigitalOcean

2
AWS

Rating is 4.9 out of 5

AWS

3
Vultr

Rating is 4.8 out of 5

Vultr

4
Cloudways

Rating is 4.7 out of 5

Cloudways


How to set cache control for static assets in Laravel?

To set cache control for static assets in Laravel, you can modify the configuration in the .htaccess file or by using middleware in your Laravel application.


To modify the .htaccess file, you can add the following lines of code to set the cache control for static assets:

1
2
3
4
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault "access plus 1 month"
</IfModule>


This will set the cache control to expire after one month, but you can customize the expiration time as needed.


Alternatively, you can create a middleware in Laravel to set cache control for static assets. Here's an example of how you can create a middleware to set cache control:

  1. Create a new middleware by running the following command:
1
php artisan make:middleware CacheControlMiddleware


  1. In the generated CacheControlMiddleware.php file, add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
namespace App\Http\Middleware;

use Closure;

class CacheControlMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->headers->set('Cache-Control', 'public, max-age=31536000');
        
        return $response;
    }
}


  1. Register the middleware in the App\Http\Kernel.php file:
1
2
3
4
5
6
protected $middlewareGroups = [
    'web' => [
        // Other middleware...
        \App\Http\Middleware\CacheControlMiddleware::class,
    ],
];


This middleware will set the cache control for static assets to public with a maximum age of one year (31536000 seconds).


Remember to adjust the cache control settings based on your specific requirements.


How to prevent caching of specific routes in Laravel?

To prevent caching of specific routes in Laravel, you can use the following middleware:

  1. Create a new middleware using the following command:
1
php artisan make:middleware DoNotCache


  1. Open the newly created middleware file (DoNotCache.php) in the App/Http/Middleware directory.
  2. Add the following code to the handle method in the middleware file to prevent caching:
1
2
3
4
5
6
7
8
public function handle($request, Closure $next)
{
    $response = $next($request);

    $response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');

    return $response;
}


  1. Register the new middleware in the $routeMiddleware array located in the app/Http/Kernel.php file:
1
2
3
protected $routeMiddleware = [
    'doNotCache' => \App\Http\Middleware\DoNotCache::class,
];


  1. Apply the doNotCache middleware to the specific routes that you want to prevent caching by adding the middleware to the route definition:
1
2
3
Route::get('/your-route', function () {
    return view('your-view');
})->middleware('doNotCache');


By following these steps, you can prevent caching of specific routes in Laravel using a custom middleware.


What is the use of cache directives in Laravel?

Cache directives in Laravel are used to control the caching behavior of responses from the server. These directives allow developers to specify how long a response should be cached for, whether it should be cached at all, and other caching-related options.


Some commonly used cache directives in Laravel include:

  • Cache::put(): Store an item in the cache for a specific number of minutes.
  • Cache::add(): Store an item in the cache only if the key does not already exist.
  • Cache::forever(): Store an item in the cache permanently.
  • Cache::remember(): Retrieve an item from the cache, or store the result of a closure if the item does not exist.
  • Cache::forget(): Remove an item from the cache.


By using these cache directives, developers can optimize the performance of their applications by caching frequently accessed data and reducing the number of database queries or API requests.

Facebook Twitter LinkedIn Telegram

Related Posts:

To remove cache in CakePHP, you can follow these steps:Locate the cache files: The cache files are typically stored in the tmp/cache directory of your CakePHP installation. Go to this directory in your project. Clear the cache manually: You can manually delete...
The buffer cache in an Oracle database is a key component of Oracle&#39;s memory architecture. It is designed to enhance database performance by reducing disk I/O operations.When data is read from disk, it is stored in memory blocks, which are then cached in t...
To remove a table from the cache in Oracle, you can use the ALTER TABLE command with the NOCACHE option. By specifying this option, you are indicating that the table should not be cached in the buffer cache. This means that data from the table will not be stor...