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 ?

有帮助吗?

解决方案

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!

其他提示

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();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top