DEV Community

Philip Perry
Philip Perry

Posted on • Originally published at programming-decoded.com on

2

Using the repository pattern in Laravel for caching

I started using the repository pattern a little while ago to provide some abstraction and so that I could have my eloquent queries in a central place. But one really nice thing about doing this that only occurred to me recently is that it allows you to centralize things like caching one’s queries. Caching one’s queries saves having to make expensive database calls. This is how my repository class looks like for getting a quiz setting:

app/Repositories/QuizSettingRepository.php

<?php
namespace App\Repositories;

use \App\Models\QuizSettings;
use \Cache;

class QuizSettingRepository implements QuizSettingRepositoryInterface
{
    public function get($quizid, $keyname)
    {
        $value = false;

        $cacheKey = 'quizsettings' . $quizid . "_" . $keyname;

        if (Cache::has($cacheKey)) {
            $value = Cache::get($cacheKey);

        } else {
            $quizsettings = QuizSettings::where('quizid', '=', $quizid)->get()->keyBy('keyname');

            if(isset($quizsettings[$keyname]))
            {
                $value = $quizsettings[$keyname]->value;
            }

            Cache::put($cacheKey, $value, now()->addSeconds(10));
        }

        return $value;
    }
}
Enter fullscreen mode Exit fullscreen mode

One could take this a step further and implement caching for all repositories in a global place using the decorator pattern as described here: https://matthewdaly.co.uk/blog/2017/03/01/decorating-laravel-repositories/

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay