Support the ongoing development of Laravel.io →
Cache Eloquent Views
Last updated 2 years ago.
0
$users = User::remeber(10,'all_users')->all();

This cache the query result to the database for 10 minutes

Last updated 2 years ago.
0

Thanks for your reply @gafitescu but actually I do not want to cache all the users info, but just avoid

SELECT * FROM `Language ` WHERE `Language `.`id` = '1' LIMIT 1

That's the language name that I actually want to cache when I access {{ $user->language->name }} from my view, not the whole user.
Basically I believe I need to find a way to overwrite what Laravel does when fetching related models info (especially from the view) and being able to add a remember() on specific functions/model attributes.

Last updated 2 years ago.
0

Not sure if it's possible the way you want it. I guess another way you can do in order to achieve this is to use Raw sql on both cases and cache only

SELECT * FROM `Language`

and reference by language id in the foreach something like :

@foreach($users as $user)  
<td>{{ $user->name }}</td>  
<td>{{ $arLanguages[$user->language_id] }}</td>  
@endforeach  
Last updated 2 years ago.
0

I get your idea, and that will surely work but I'm looking for a cleaner solution. I don't want to have to use this array everytime I try to access {{ $user->language->name }}

Last updated 2 years ago.
0

Why not use Eager loading?

$users = User::with('language')->get();

If you cache that object, it already has the relations loaded.

Last updated 2 years ago.
0

I should be using eager loading indeed, instead of making a request on each iteration in the loop, I will amend that but the main question is still the same, can I cache only the ::with('language') by adding a ->remember(10) for instance (forever would be perfect)?

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

nikospkrk nikospkrk Joined 13 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.