In this episode, we're diving into how Laravel retrieves the authenticated user on every request—and how you can speed this up by caching. Out of the box, Laravel uses a database query to load your user each time, which is usually fine, but in high-traffic apps, this can become a bottleneck.
We'll walk through setting up Laravel Debug Bar so we can clearly see those user queries in action. Then, we'll explore how Laravel's authentication works under the hood, specifically via the Eloquent user provider. Instead of modifying core Laravel code, the episode shows how to extend the Eloquent user provider to add a caching layer, so after the first request, subsequent requests pull the user from cache instead of banging the database every time.
You'll see how to create a custom provider, override the relevant method, and use Laravel's cache system (with your choice of cache driver!) to store the retrieved user. We'll also cover a crucial part: cache busting. Simply caching the user isn't enough—you have to make sure you clear the cache when the user is updated or deleted to avoid serving stale data. This is accomplished using model observers that hook into Laravel's event system.
The episode wraps up by stressing that this technique is for special cases—there are some real sharp edges if you forget to clear the cache in custom update situations, but for apps with lots of authenticated users and performance concerns, adding a caching layer to your auth provider is a powerful tool.