0
0
Laravelframework~30 mins

Why caching reduces response times in Laravel - See It in Action

Choose your learning style9 modes available
Why caching reduces response times in Laravel
📖 Scenario: You are building a Laravel web application that shows a list of popular books. Each time a user visits the page, the app fetches the book list from the database. To make the page load faster, you want to use caching to store the book list temporarily.
🎯 Goal: Build a simple Laravel controller method that fetches a list of books from the database and caches the result. This will reduce response times by avoiding repeated database queries.
📋 What You'll Learn
Create a variable with a list of books (simulate with an array)
Add a cache key name variable
Use Laravel's cache to store and retrieve the book list
Return the cached or fresh book list
💡 Why This Matters
🌍 Real World
Caching is used in web apps to store frequently requested data temporarily. This avoids repeated slow database queries and makes pages load faster for users.
💼 Career
Understanding caching is important for backend developers to optimize app performance and improve user experience.
Progress0 / 4 steps
1
Create the initial book list data
Create a variable called $books and assign it an array with these exact values: 'The Hobbit', '1984', 'Pride and Prejudice'.
Laravel
Need a hint?

Use square brackets to create an array with the exact book titles.

2
Add a cache key variable
Add a variable called $cacheKey and set it to the string 'popular_books' inside the index method.
Laravel
Need a hint?

Use a simple string variable to hold the cache key name.

3
Use Laravel cache to store and retrieve the book list
Use Laravel's cache()->remember() method with $cacheKey and a closure that returns $books. Set the cache time to 60 seconds. Assign the result to a variable called $cachedBooks.
Laravel
Need a hint?

Use cache()->remember() with a closure that returns the books array.

4
Return the cached book list
Add a return statement that returns the $cachedBooks variable from the index method.
Laravel
Need a hint?

Use a simple return statement to send the cached books back.