How does Laravel 4 cache queries work?

Asked

Viewed 288 times

6

I’m trying to cache my query, but I don’t know how to recover the data later. Another question: when the number of rows in the database increases, it automatically caches the query, or every time I enter the page it caches the query again?

$value = Cache::remember('users', 50, function()
{
    return DB::table('users')->with('ucomments')->get();
});
  • 5

    To the Laravel community: We are discussing something relevant with your tag here: http://meta.answall.com/questions/310/como-trata-tags-em-arvore. And we still have important information for you here: http://meta.answall.com/questions/300/diretrizes-for-creation-tag-wikis. I take this opportunity to congratulate everyone for what they are doing here at Sopt.

2 answers

6


By making use of the method remember, the created cache is only maintained by the number of minutes passed in the parameter $minutes:

$value = Cache::remember('users', $minutes, function()
{
    return DB::table('users')->with('ucomments')->get();
});

How did you pass 50, after 50 minutes the cache will be rewritten with the result of a new query to the table users.

Notes:

  • As long as the number of minutes indicated does not pass, the cache query will not be updated.

  • In the course of that time the cache query is not updated, this would go against the goal of caching something.


Collect

To collect the key users you can use:

$value = Cache::get('users');

Interesting:

  • 1

    @Hernandes It is best to avoid converting a response from pt_PT to pt_BR. To discuss this subject, please visit our goal, especially this question: http://meta.answall.com/questions/292/revisao-de-questions-ou-respostas-em-pt-para-pt-br-ou-vice-versa-howto take action

  • Until then I thought that the main focus was pt_BR(.UTF-8) I am in no way against covering other Portuguese-speaking countries in general ( until because the language is Portuguese and not Brazilian, rsrs). But we must cherish the non-use of regional language vices.

  • But @Ernandes, what addictions? It is a good discussion for the goal, you should post something there. In this answer I see no addictions, only regional differences. No grammar error (syntax, spelling, etc).

  • 1

    @bfavaretto, said it is interesting not to use such addictions, and not that the answer in question contained them, I will post in the Meta not to take the focus of the question.

2

I usually use the method member($min) in the query itself.

DB::table('users')->with('ucomments')->remember(10)->get();

The Laravel will store a cache of your query for 10 minutes.

I find this the most practical and easy method.

Documentation Laravel query cache

Browser other questions tagged

You are not signed in. Login or sign up in order to post.