Aakash
Aakash

Reputation: 226

Caching Lazy Eager Loading Queries in Laravel 5.1

How do I cache the lazy eager loading queries based on the model relationships. For example -

$books = App\Book::all();

$books->load('author', 'publisher');

I can cache the first query with something like this

$books = Cache::remember('allbooks', 60, function() {
             return App\Book::all();
         });

How do I cache the second query?

If there is no direct way, please suggest any workaround, possibly with a sample code.

Update: I need the second query to be executed separately so I can clear these two cache keys separately.

Upvotes: 2

Views: 894

Answers (1)

Antonio Madonna
Antonio Madonna

Reputation: 919

You can use the query builder with method:

$books = App\Book::with(['author','publisher'])->get();

Or simply do the additional load inside the cache callable:

$books = Cache::remember('allbooks', 60, function() {
     return App\Book::all()->load('author', 'publisher');
});

Update: to keep the caches separated you need two variables, like this:

$books = Cache::remember('allbooks', 60, function() 
{
     return App\Book::all();
});
$booksAP = Cache::remember('allbooks_ap', 60, function() use ($books)
{
     return $books->load('author', 'publisher');
});

Upvotes: 3

Related Questions