Cache API Resource
I am wondering how can I use 'Cache::remember' on an API Resource?
My setup is pretty modular for the example of a users Profile in the sense that the Profile is made up of 10 - 15 separate Models
So basic idea is from UsersController:
public function show(Request $request, Profile $profile)
{
// RETURN FULL PROFILE FORMATTED RESOURCE
PublicProfileResource::withoutWrapping();
return new PublicProfileResource($profile);
}
And the resource is:
$response = [
'type' => 'bio',
'attributes' => $attributes,
'relationships' => [
'rates' => new PublicRatesCollection($this->rate),
'contact' => new PublicContactResource($this->contact),
.... and 15 other as above making up the users complete profile
return $response;
Everything in terms of fetching the data and returning the resource is working, but since the profile is viewed about 1000:1 update it only makes sense to Cache the full PublicProfileResource($profile);
I thought to before passing $profile to the Resource to manually build a full complete $query, Cache the results then pass that to the Resoure but each individual query still gets executed when calling as above
So second attempt controller method looked like:
public function display(Request $request, Profile $profile){
$key = $profile->slug . '_profile_cache';
$data = Cache::remember($key, 60, function () use($request, $profile){
// getPublicProfile is a hardcoded query that already includes all the individual Models ( rates, contact and the other 15)
return $profile->getPublicProfile($request, $profile);
});
// RETURN FULL PROFILE FORMATTED RESOURCE
CachePublicProfileCollection::withoutWrapping();
return new CachePublicProfileCollection($data);
}
But the problem, is the individual queries still get executed inside the Resource even when the data is cached and passed
'rates' => new PublicRatesCollection($this->rate), // triggers a query yet the rate has been passed
'contact' => new PublicContactResource($this->contact), // triggers a query yet the contact has been passed
Any ideas?
Please or to participate in this conversation.