Home > Mobile >  Load blade view file from cache in Laravel
Load blade view file from cache in Laravel

Time:04-14

I'm trying to store a whole blade view with param in cache for first load and load it from cache in next time reload.

Here is what I did:

public function cacheAction()
{
    $data = $this->model->getContent();
    Cache::remember('cache-view', 1800, function() {
        dd('load from cache!');
        return view('index')->render();
    });
    dd('not load from cache!');
    return view('index', ['data' => $data]);
    
}

I added 2 lines debug notice when load page. But when I access page, it always show "not loaded from cache!" for anytime.

How I can fix this?

Thank you very much!

CodePudding user response:

You have it the other way around here. When your function in the remember callback runs then it is not loaded from cache. When it does not run then it is loaded from cache. However you are not actually using the result from the cache here. Here's what you can do to utilise the cache:

public function cacheAction()
{
    $view = Cache::remember('cache-view', 1800, function() {
        $data = $this->model->getContent();
        return view('index', ['data' => $data]);
    });
    return $view;    
}

Note that your cache-view cache key does not actually depend on the content of $data so if $data changes you will get a stale cached view. Here's how to get around this:

public function cacheAction()
{
    $data = $this->model->getContent();
    $cacheKey = md5(serialize($data)); // Make sure data is serializable
    $view = Cache::remember('cache-view-'.$cacheKey, 1800, function() use ($data) {
        return view('index', ['data' => $data]);
    });
    return $view;    
}

However this does have the drawback of always reading $data to check if the cache is stale. Which solution works for you depends on how static or dynamic your data is. If you don't expect data to change frequently then people seeing stale data for at most 1800 seconds might not be a big issue

CodePudding user response:

You need to use the return value of the remember function: you will always get to the dd() function because the return statement is inside the remember callback function.

public function cacheAction()
{
    
    $return = Cache::remember('cache-view', 1800, function() {
        dump('new cache created');
        $data = $this->model->getContent();
        return view('index', ['data' => $data]);
    });
    dd('this will show every time, even if loaded by cache');
    return $return;
    
}
  • Related