How to create Laravel search by taking data from the cache?

Asked

Viewed 275 times

0

Since I have this data in a file I see no reason 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 searching the database data: $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 how to proceed, I appreciate any help :).

1 answer

1

Doing a little research I found a solution that might suit you.

Instead of searching 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 by searching 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 description, you can ride your route so:

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

There are other options for you as well Laravel Scout, but I believe he doesn’t cover his need but it’s worth taking a look.

Response based on this source.

  • I had already come across this post however and I thought it would not be so interesting because create a new cache every query your tip to change my approach with Laravel Scout seems to me to be the solution to my problem, Thanks Vinicius Lourenço :).

Browser other questions tagged

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