A
A
Analka2022-02-22 11:04:31
Laravel
Analka, 2022-02-22 11:04:31

Request repetition and caching?

Hello. The question arose

, I often repeat this request

Article::find($id);

, I want to cache it, but what if it sits in several services and controllers?

I thought to put it in the ArticleQuery.php class and store queries on the Article model there

class ArticleQuery 
{
   public function getById(int $id) {
      Cache::remember('article_'.$id, $minutes, function () {
        return Article::find($id);
     });
   }
}


and call already like
$articleQuery->getById($id)

How does anyone solve such problems?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
pLavrenov, 2022-02-22
@Analka

This is solved like this
. In fact, this is a data acquisition layer. in controllers, it will be necessary to receive from the repository, and then if you need to change the way the records are received (or, for example, the cache key), it will be enough to change only in the repository.
And there is an error in your code. ID is not passed to the callback and $minutes does not exist at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question