Question

I know you can cache a query by appending ->remember($minutes).

However, this doesn't work when using loading on an existing Eloquent result. This is because load doesn't return a querybuilder but directly executes it.

Say you want to load the friends of a user:

$user=Auth::user();
$user->load('friends');  // How to cache these results ?

How can I cache these ?

Was it helpful?

Solution

You can't using this code on its own. You do have two options, though:

1) Wrap your code in a wrapper somewhere (essentially abstracting away this call), which does a cache check first, and runs these queries if the cached item does not exist or is expired.

2) Extend the Auth library, specifically its EloquentUserProvider class, and modify the query performed by the retrieveById() method.

You can see one method of abstracting methods and caching in Chris Fidao's Implementing Laravel. The accompanying book is handy!

OTHER TIPS

You have to convert User object into QueryBuilder to get access to ->remember() method Try

    User::with('friends')->where('id', Auth::user()->id)->remember()->first();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top