Clearing the cache in Drupal is a common task to ensure that changes to the site configuration, code, or content are reflected immediately. Here are several methods to clear the cache in Drupal:

Using the Admin Interface

  1. Performance Page:
  • Navigate to Administration > Configuration > Development > Performance (/admin/config/development/performance).
  • Click the “Clear all caches” button.

Using Drush

Drush is a command-line shell and scripting interface for Drupal. It provides an efficient way to interact with your Drupal site.

  1. Clear Cache Command:
  • Open your terminal or command line interface.
  • Navigate to your Drupal site’s root directory.
  • Run the following command:
    sh drush cr
    This command clears all caches.

Using Drush in Drupal 7

If you are using Drupal 7, the command is slightly different:

  1. Clear Cache Command:
  • Open your terminal or command line interface.
  • Navigate to your Drupal site’s root directory.
  • Run the following command:
    sh drush cc all

Using the Rebuild.php Script

Drupal provides a rebuild.php script that can be used to clear caches in cases where the admin interface or Drush is not accessible.

  1. Rebuild Script:
  • Access the rebuild.php script by navigating to http://example.com/core/rebuild.php (for Drupal 8 and above) or http://example.com/rebuild.php (for Drupal 7).

Programmatically Clear Cache

You can clear the cache programmatically in a custom module or a theme by using Drupal’s API.

  1. Custom Code:
  • Use the following code snippet in a custom module to clear all caches:
    php \Drupal::service('cache.render')->invalidateAll(); \Drupal::service('cache.page')->invalidateAll(); \Drupal::service('cache.dynamic_page_cache')->invalidateAll();
  • Or, use this command to clear specific caches:
    php \Drupal::cache()->invalidateAll();

Clear Cache Tables Directly in the Database

This method should be used as a last resort and with caution, as it involves direct database manipulation.

  1. Using SQL Commands:
  • Access your database using a tool like phpMyAdmin or the MySQL command line.
  • Run SQL commands to truncate cache tables. For example:
    sql TRUNCATE cache_config; TRUNCATE cache_container; TRUNCATE cache_data; TRUNCATE cache_default; TRUNCATE cache_discovery; TRUNCATE cache_dynamic_page_cache; TRUNCATE cache_entity; TRUNCATE cache_menu; TRUNCATE cache_render; TRUNCATE cache_toolbar;

Choose the method that best fits your situation and environment. The admin interface and Drush are the most commonly used and safest methods for clearing the cache.

Tagged in:

,