Laravel 10 -How to use Laravel's Caching Features to Improve Performance

Laravel 10 -How to use Laravel's Caching Features to Improve Performance

Set up the Caching Feature in Laravel

To enable caching in Laravel, we need to configure the caching driver in the .env file. Laravel supports various caching drivers such as file, database, Redis, and Memcached. Here’s an example of how to enable

 the file driver for caching:

CACHE_DRIVER=file

Once the caching driver is set, we can proceed with using the caching features in Laravel.

Caching Queries

Laravel allows you to cache database queries to improve performance, especially when the same query is used multiple times throughout the application. Here's an example of how to cache a query:

$users = Cache::remember('users', 60, function () { return DB::table('users')->get(); });

In this example:

  • remember() caches the query result for 60 seconds.

  • The first argument ('users') is the cache key used to retrieve the cached data.

  • The second argument (60) is the cache expiration time in seconds.

  • The third argument is a closure that executes the query and returns the result.

Cache Tags

Laravel's caching system also supports cache tags, which are useful for grouping related cache items. This allows you to easily clear all cache items associated with a specific tag. Here’s an example of how to use cache tags:

Cache::tags(['users', 'admins'])->put('john', $user, 60);

In this example:

  • put() caches the $user object with the key 'john' for 60 seconds.

  • The cache is tagged with both users and admins, making it easy to clear all cache items with these tags.

To clear the cache for a specific tag, you can use the forgetTag() method:

Cache::forgetTag('users');

This will clear all cache items tagged with 'users'.

Conclusion

I hope this tutorial helps you in setting up and utilizing caching in your Laravel applications. Caching queries and using cache tags can significantly improve performance and make it easier to manage your application’s cached data. Thanks for reading, and thank you for your continued support! šŸ™‚

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close