In PHP, how do I cache objects in Laravel?

In Laravel, you can cache objects using the built-in caching system that provides a simple and expressive interface for different cache backends. This allows you to store any data temporarily to reduce the number of database queries or computationally expensive operations, thereby improving your application's performance.

Example

// Storing an object in cache for 10 minutes use Illuminate\Support\Facades\Cache; $user = User::find(1); // Example user fetch Cache::put('user_1', $user, 600); // Cache for 10 minutes (600 seconds) // Retrieving the cached object $cachedUser = Cache::get('user_1'); if ($cachedUser) { // Use the cached object echo $cachedUser->name; // Accessing user name } else { // Cache miss, fetch from DB again $user = User::find(1); Cache::put('user_1', $user, 600); }

caching Laravel objects performance Cache facade