How to create search in Laravel getting cache data?

0

Since I have this data in a file I do not see why to make a request in the database.

Example of my curly code: $produtos = Cache::rememberForever('produtos', function () { return DB::table('produtos') ->get(); }); $produtos = \Cache::get('produtos');

Example of my code that fetches the data from the database: $produtos = Produto::where('titulo', 'like', '%'.Input::get('texto').'%') ->orWhere('descricao', 'like', '%'.Input::get('texto').'%') ->get();

I tried to do something like this: $produtos = \Cache::get('produtos')->where('titulo', 'like', '%'.Input::get('texto').'%');

But without success, someone would have a suggestion of how to proceed, I thank you for any help:

    
asked by anonymous 04.09.2018 / 19:34

1 answer

1

Doing a light search I found a solution that can serve you.

Instead of doing a search in your cache, you can store the search using your url as a key the first time you ask for it, and the second time it does the same search, you return the data when making a search for the url in the cache.

// Primeiro ele pega o url da requisição
$url = request()->url();

// Depois os parametros de query da requisição
$queryParams = request()->query();

// Ordena os parametros
ksort($queryParams);

// E torna em string os parametros ordenados
$queryString = http_build_query($queryParams);

// Monta o url completo junto com os parametros
$fullUrl = "{$url}?{$queryString}";

// Encripta o url em sha1 para facilitar o armazenamento
$rememberKey = sha1($fullUrl);

// Em seguida faz Cache e depois retorna o valor armazenado.
return Cache::rememberForever($rememberKey, function () use ($data) {
    return $data;
});

In the original post, it stored results from a pagination. As you want to search the title and the description, you can mount your route like this:

Route::get('/path/{titulo?}/{descricao?}', 'Controller@index');

There are other options for you too, such as Laravel Scout , but I do not think it will cover your need but it's worth it take a look.

Answer based on this source .

    
05.09.2018 / 18:22