S
S
SvizzZzy2017-08-07 22:16:54
Laravel
SvizzZzy, 2017-08-07 22:16:54

What is the best way to cache views in Laravel 5.4?

There is a part of the page with large complex queries, I cache its query data in redis in this way:

$cache = cache("page-{$product->id}");
        if (!$cache){

          $view = view('product.index', ['product' => $product])->render();
          cache(["page-{$product->id}" => $view], 180);

        }else{

           $view = $cache;
        }

return  $view;

In this case, all html code will be added to the radish.
I also thought about adding only $product to the cache (model collection, without render view), but then even more garbage is added, unnecessary information about belongsToMany relationships, etc., and the size of the cache entry becomes huge and 90% unnecessary.
Is there a more elegant way, or is it okay?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Talalaev, 2017-08-07
@SvizzZzy

It’s hard for you to write, it can be simpler:

$view = cache("page-{$product->id}", function () {
    $view = view('product.index', ['product' => $product])->render();
    cache(["page-{$product->id}" => $view], 180);
    return $view;
});
return  $view;

And as for the main question, it’s strictly individual here, you provided too little data, little data, you can explore for a long time how best, and so on.
But in general, caching the entire html (relatively speaking) page is ok, it allows you to SIGNIFICANTLY speed up the site, especially when you need to update the material less (let's say the news page, without comments). Well, as for the memory consumption, well, how else, the whole point of caching is less processor consumption, more RAM consumption.

M
Mikhail Nosov, 2018-12-04
@WebSEOkz

I support SvizzZzy and I can't find the right answer anywhere.
If I don’t want to cache the entire page, but I want to cache only a separate html piece, then how to organize it, because the view creates the entire page, and if you cache separate collections of models, then the cache is actually clogged with unnecessary information.
How to display a page consisting of separate cached blocks?
A good example is the site menu, which is the same for all pages, rarely changes, but is compiled by large queries in the database and links of different nesting levels of pages and categories. If I need to cache the top menu, content and footer of the site separately, how can I do this and then display it in the view?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question