Joshua Wallace

Search

Engineer & Developer

Caching users in Laravel to reduce query load

If you’ve used Laravel for any length of time, you’ve typed Auth::user() at least once. When a request is made, Laravel will attempt to resolve the currently authenticated user using a single query from the database and returns to you your User model. Something like this will be run:

User::query()->find($key);

This will run a single query on each request, so whenever you access the currently authenticated user, you can be sure you’re accessing the same instance. By itself, this is perfectly fine. The query has no joins, subqueries or other dependencies. It’s as simple as find a user by the given guard. But, what if you needed more information about the user?

This now executes extra queries of data which is relatively static. The more information you need, the more queries you’ll need to run, and the more data you’ll need to fetch.