Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search in data from cache

My question is, if there is data in the cache, I created a condition by saying fetch, and if not, I bring it from the database and refresh the cache for a certain period of time. Normally, if I don’t use the cache, I can search the page, but I cannot search by id or nickname with the code below.So when using cache::get can I add a search condition?

public function index(Request $request)
    {
        $submit = $request->get('submit');
        $id = $request->get('id');
        $nick_name = $request->get('nick_name');

        if (Cache::has('users')) {
            $users = Cache::get('users');
            return view('admin.users.index', compact('users'));
        }

        $users = User::when(!empty($id), function ($query) use ($id) {
            $query->where('id', $id);
        })->when(!empty($nick_name), function ($query) use ($nick_name) {
            $query->where('nick_name', $nick_name);
        })->orderBy('created_at', 'asc')->get();


        Cache::put('users', $users, now()->addMinutes(60));
        return view('admin.users.index', compact('users'));
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should add search criteria in your cache key. E.g.

public function index(Request $request) {
    $submit = $request->get('submit');
    $id = $request->get('id');
    $nick_name = $request->get('nick_name');

    $cacheKey = User::class . md5(json_encode([$submit, $id, $nick_name]));

    if (Cache::has($cacheKey)) {
    /* ... */
}

because now your cache writes only first search result and ignores everything else.


Or write to cache all users. Then run that array through array_filter applying filters. But that can be waste of developer time if search is very dynamic.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading