<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mazen Touati on Medium]]></title>
        <description><![CDATA[Stories by Mazen Touati on Medium]]></description>
        <link>https://medium.com/@sunchayn?source=rss-7928fab44e3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*__1SE8dfUF6446z9F0sFaQ.jpeg</url>
            <title>Stories by Mazen Touati on Medium</title>
            <link>https://medium.com/@sunchayn?source=rss-7928fab44e3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:44:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sunchayn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introducing Nimbus: An integrated, in-browser API client for Laravel with a touch of magic]]></title>
            <link>https://sunchayn.medium.com/introducing-nimbus-an-integrated-in-browser-api-client-for-laravel-with-a-touch-of-magic-b9e348abf10d?source=rss-7928fab44e3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e348abf10d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mazen Touati]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 00:20:57 GMT</pubDate>
            <atom:updated>2025-10-24T08:30:24.744Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing APIs shouldn’t feel like a chore. Yet, here we are, copy-pasting URLs into Postman, manually typing headers, rebuilding request bodies from scratch, and constantly switching between our code and external tools. It’s 2025, and we’re still doing this.</p><p>What if your API client just… knew about your Laravel app?</p><p>That’s <a href="https://nimbus.sunchayn.io/">Nimbus</a>. An integrated, in-browser API client that automatically discovers your routes and validation rules, understands your authentication, and gives you an interface to test everything without leaving your development environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxytwHhKl9U0d1zvLTa9ww.jpeg" /></figure><h3>The Problem With Traditional API Clients</h3><p>Don’t get me wrong, tools like Postman and Insomnia are great tools. I have been using them all this time. But they’re built for a different problem; they’re generic clients meant to work with any API, anywhere. That generality comes at a cost: <strong>everything is manual </strong><em>(including the creation of scripts manually)</em>.</p><p>Think about this workflow:</p><p>You build a new endpoint in Laravel. You define the route, write the controller, and create a Form Request with validation rules. Then you switch to your API client and… start from scratch. Copy the URL. Type the method. Add headers one by one. Build the request body by guessing what fields you need. Send the request. Get a validation error. Go back to your code to check the validation rules. Update your request. Try again. Then, once done, you have to figure out how to communicate it with the rest of the team.</p><p>That’s a lot of friction and wasted time.</p><p>Here’s the thing: your Laravel application already knows everything about your API. It knows the routes, the validation rules, the authentication requirements, and the response structure. Why are we manually reconstructing this information in an external tool?</p><p><strong>That was what I was asking myself every time I was fiddling with these tools. Which made me think, why not make it happen?</strong></p><blockquote>Note: The above-mentioned workflow describes a situation where you want to interact and inspect the API. It doesn’t suggest not having unit and integation tests to validate the implementation.</blockquote><h3>Meet Nimbus</h3><p><a href="https://nimbus.sunchayn.io/">Nimbus</a> takes a different approach: instead of being a generic API client, it’s a <strong>Laravel-aware API client</strong>. It lives inside your application and automatically understands what you’re building.</p><p>Here’s what happens when you install Nimbus:</p><ol><li>It scans your API routes.</li><li>It extracts validation rules from Form Requests and inline validators.</li><li>It builds JSON schemas automatically.</li><li>It gives you an interface to test everything.</li></ol><p>That is it. No collections to maintain. No manual syncing. Just install and start testing.</p><p>Want to see it in action before installing? Try the <a href="https://nimbus.sunchayn.io/demo/">live demo</a>. No setup required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*duQ9LfrB8T35EZAEhGREPw.gif" /><figcaption>Animated demo</figcaption></figure><h4>The Magic of Laravel-Awareness</h4><p>Being inside your Laravel application gives Nimbus superpowers that external clients can’t have:</p><ul><li>Session-based authentication</li><li>User impersonation</li><li>Cookie inspection</li></ul><p>Let me show you what this means in practice.</p><p><strong>Setting up a new endpoint?</strong></p><p>With traditional tools, you manually configure everything: copy URLs, set HTTP methods, add headers one by one, and build request bodies by guessing field names. With Nimbus, routes are discovered automatically.</p><p><strong>Updating validation rules?</strong></p><p>Changed a field from optional to required? With traditional tools, you need to manually update your collection and sync it with your team. With Nimbus, the changes appear immediately. It reads directly from your validation rules.</p><p><strong>Testing authenticated endpoints?</strong></p><p>Traditional tools require extracting tokens, managing expiration, and manually adding authorization headers. Nimbus lets you authenticate with one click, either as your current user or by impersonating any user ID. No token management needed.</p><p><strong>Debugging cookies?</strong></p><p>Need to inspect a Laravel session cookie? With external tools, you copy the encrypted value, find (or make) a decoder, paste it somewhere, and try to make sense of it. Nimbus decrypts and displays your cookies automatically.</p><p><strong>Sharing with your team?</strong></p><p>Traditional tools require exporting collections, sending files around, and hoping everyone imports the latest version. With Nimbus, there’s nothing to share. Everyone on the team just visits /nimbus in their local environment. No exports, no imports, no version mismatches.</p><p>—</p><p>And honestly, the <a href="https://github.com/sunchayn/nimbus/discussions/1">sky is the limit</a>. The package embraces a “not afraid of magic” philosophy, and anything that we can do to make the Developer Experience much better, we will do.</p><h3>What Nimbus Is NOT</h3><p>Let’s be clear about this: <strong>Nimbus is not an API documentation generator</strong>.</p><p>It doesn’t produce beautiful, client-facing API documentation. It’s not trying to replace tools like <a href="https://scribe.knuckles.wtf/laravel">Scribe</a> or <a href="https://scramble.dedoc.co/usage/getting-started">Scramble</a>. Its sole purpose is to improve the developer experience while building and testing APIs.</p><p>Think of it as a developer-focused API playground, not a production documentation tool.</p><h3>Getting Started</h3><p>Installation takes less than a minute:</p><pre>composer require sunchayn/nimbus<br><br>php artisan vendor:publish --tag=nimbus-assets --tag=nimbus-config</pre><p>That’s it. Navigate to http://your-app.test/nimbus and start testing.</p><p>Nimbus is currently an open alpha release. This means:</p><ul><li>You might encounter bugs or unexpected behaviors.</li><li>Some edge cases aren’t handled yet</li><li>Performance could be better for large applications</li><li>Features are intentionally minimal to validate the concept.</li></ul><p>I’m releasing it as alpha to validate whether this approach resonates with the Laravel community. Does automatic schema discovery actually improve your workflow? What features would make it indispensable?</p><h3>Closing Notes</h3><p>We spend so much time building APIs in Laravel. Yet we’ve accepted that testing them requires leaving our environment, reconstructing our routes manually, and fighting with external tools that don’t understand our application.</p><p>Nimbus is my attempt to eliminate that friction. Give it a try. It takes less than a minute:</p><p>Nimbus is my attempt to eliminate that friction. Give it a try.</p><p><strong>Links:</strong></p><ul><li>Documentation: <a href="https://github.com/sunchayn/nimbus/wiki/user-guide">User Guide</a></li><li>Want to contribute? <a href="https://github.com/sunchayn/nimbus/wiki/contribution-guide">Check the contributor guide</a></li><li>Found a bug? <a href="https://github.com/sunchayn/nimbus/issues">Open an issue</a></li><li>Have a feature idea? <a href="https://github.com/sunchayn/nimbus/discussions">Start a discussion</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e348abf10d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unorthodox Monoliths in Laravel]]></title>
            <link>https://medium.com/studocu-techblog/unorthodox-monoliths-in-laravel-ebb41277780e?source=rss-7928fab44e3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebb41277780e</guid>
            <category><![CDATA[database-optimization]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Mazen Touati]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 11:30:10 GMT</pubDate>
            <atom:updated>2025-02-05T11:30:10.469Z</atom:updated>
            <content:encoded><![CDATA[<p>Laravel is often synonymous with simplicity and developer-friendly experience. But what happens when your application scales far beyond what Laravel’s default patterns provide? At <a href="https://studocu.com/">Studocu</a>, we’ve pushed the boundaries of what’s considered “standard” in Laravel development to keep our growing monolith efficient, maintainable, and evolving.</p><p>In this article, I’ll share some unconventional practices and techniques we’ve embraced that might make you rethink how you approach your Laravel projects. Whether navigating scaling challenges or just curious how far you can stretch Laravel, there’s something here for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pf-6dQL-UENvRo0cDY9BYA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sunx?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Li Zhang</a> on <a href="https://unsplash.com/photos/an-abstract-red-and-orange-background-with-curves-K-DwbsTXliY?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In this article we will learn about:</p><ul><li>Multi-Application Infrastructure</li><li>Circuit-Breaker (fuse) for Distributed Databases</li><li>Hybrid Optimizations When MySQL Alone Isn’t Enough</li></ul><h3>1. Multi-Application Infrastructure</h3><p>By default, Laravel ships with a single application and shared service providers. However, as projects grow, you might end up with multiple applications within the same Laravel codebase. Think of the main website, a CMS, a Webhooks service, etc. Initially, this setup works fine, but as performance becomes critical and different applications evolve at different paces, you may need a more isolated approach.</p><p>In our case, we’re migrating incrementally to a Next.js frontend powered by a REST API, while still maintaining and evolving our Laravel monolith. The simplest and most efficient solution was embedding the REST API within the monolith itself, reusing the same infrastructure, configuration, and models to keep everything in sync.</p><p>This approach worked well until our REST API started conflicting with other applications due to the shared core middleware and HTTP Kernel. To solve this, we needed a way to boot the REST API separately while keeping it inside the monolith.</p><p>Plus we were faced with two facts:</p><ul><li>Rest API expects larger traffic than the rest of the applications, which means the faster it is the better.</li><li>We don’t need to support heavy and diverse features in Rest, such as CMS services, UI services, Translation services, etc.</li></ul><h4>1.1. The Solution: Multi-Application Bootstrapping</h4><p>The key idea is to spawn a separate Laravel application instance for the REST API with its own HTTP Kernel and exception handler. This allows isolating its global middleware, service providers, and error handling from the other applications.</p><p>This not only improves performance but also makes the code much more readable. We eliminate any possible conditional logic that might arise in the codebase to give Rest API a slightly different treatment and vice-versa.</p><p><strong>How Laravel Handles Requests</strong></p><p>Laravel is a front-controller framework, meaning every request first hits ./public/index.php, where Laravel:</p><ol><li>Captures the request</li><li>Instantiates the application</li><li>Creates the Kernel</li><li>Handles the request and returns a response</li></ol><p>A simplified version of this process looks like:</p><pre>&lt;?php<br><br>$app = require_once __DIR__.&#39;/../bootstrap/app.php&#39;;<br><br>$kernel = $app-&gt;make(Kernel::class);<br><br>$response = $kernel-&gt;handle(<br>    $request = Request::capture()<br>)-&gt;send();<br><br>$kernel-&gt;terminate($request, $response);</pre><p>This is where we introduce our multi-application logic. We check whether the request is for the REST API and load a separate application instance if needed:</p><pre>$request = Request::capture();<br><br>$isRest = $request &amp;&amp; str_starts_with($request-&gt;getRequestUri(), &#39;/rest-api&#39;);<br><br>$app = $isRest<br>    ? require_once __DIR__ . &#39;/../bootstrap/rest-app.php&#39;<br>    : require_once __DIR__ . &#39;/../bootstrap/app.php&#39;;<br><br>$kernel = $app-&gt;make(Kernel::class);<br><br>$response = $kernel<br>    -&gt;handle($request)<br>    -&gt;send();</pre><p>The key difference here is that REST API requests load bootstrap/rest-app.php, while other requests load the default Laravel app.</p><p><strong>Booting a Separate Application</strong></p><p>Inside bootstrap/rest-app.php, we define a custom application instance:</p><pre>&lt;?php<br><br>// rest-api.php<br><br>$app = new App\Http\RestApi\RestApiApplication(<br>    $_SERVER[&#39;APP_BASE_PATH&#39;] ?? dirname(__DIR__)<br>);<br><br>$app-&gt;singleton(<br>    Illuminate\Contracts\Http\Kernel::class,<br>    App\Http\RestApi\Kernel::class<br>);<br><br>$app-&gt;singleton(<br>    Illuminate\Contracts\Debug\ExceptionHandler::class,<br>    App\Exceptions\RestApiHandler::class<br>);<br><br>return $app;</pre><p>This achieves three things:</p><ol><li>It creates a custom RestApiApplication instance.</li><li>It binds a separate HTTP Kernel for handling requests.</li><li>It registers a separate exception handler.</li></ol><p>By isolating the REST API, we ensure it has its own middleware stack and error handling without affecting the rest of the monolith.</p><h4>1.2. Customizing Service Providers</h4><p>To take this further, we customize the RestApiApplication class to load only the necessary service providers:</p><pre>&lt;?php<br><br>namespace App\Http\RestAPI;<br><br>use Illuminate\Foundation\Application as BaseApplication;<br><br>class RestApiApplication extends BaseApplication  <br>{  <br>    public function registerConfiguredProviders(): void  <br>    {  <br>        parent::registerConfiguredProviders();  <br><br>        foreach (config(&#39;app.contextual_providers.rest-api&#39;, []) as $provider) {  <br>            $this-&gt;register($provider);  <br>        }  <br>    }  <br>}</pre><p>The app.contextual_providers.rest-api config defines which service providers to load specifically for the REST API.</p><p><strong>Configuring Providers Per Application</strong></p><p>Our config/app.php file now includes:</p><pre>&#39;providers&#39; =&gt; [<br>    /*  <br>     * Core Services Providers.<br>     * These are the providers used by all applications.<br>     * Don&#39;t register anything freely here. Check `app.contextual_providers` first for contextual providers.<br>     */<br><br>    Illuminate\Auth\AuthServiceProvider::class,  <br>    Illuminate\Bus\BusServiceProvider::class,  <br>    Illuminate\Broadcasting\BroadcastServiceProvider::class,  <br>    Illuminate\Cache\CacheServiceProvider::class,  <br>    Illuminate\Session\SessionServiceProvider::class,  <br>    Illuminate\Cookie\CookieServiceProvider::class,  <br>    Illuminate\Database\DatabaseServiceProvider::class,  <br>    Illuminate\Encryption\EncryptionServiceProvider::class,  <br>    Illuminate\Filesystem\FilesystemServiceProvider::class,  <br>    Illuminate\Foundation\Providers\FoundationServiceProvider::class,  <br>    Illuminate\Hashing\HashServiceProvider::class,  <br>    Illuminate\Pagination\PaginationServiceProvider::class,  <br>    Illuminate\Queue\QueueServiceProvider::class,  <br>    Illuminate\Redis\RedisServiceProvider::class,  <br>    Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,  <br>    Illuminate\Validation\ValidationServiceProvider::class,  <br>    App\Providers\RouteServiceProvider::class,  <br>    App\Providers\StorageServiceProvider::class,  <br>    Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,  <br>    App\Providers\AuthServiceProvider::class,<br>    Illuminate\Mail\MailServiceProvider::class,<br><br>    // As per Laravel 10, these are bound in a deep level. So we need to keep them.<br>    // They are however not ideal for all applications.<br>    // e.g. The Rest API is translation agnostic and doesn&#39;t render UI components.<br>    App\Providers\TranslationServiceProvider::class,<br>    Illuminate\View\ViewServiceProvider::class,  <br>],  <br><br>&#39;contextual_providers&#39; =&gt; [  <br>    &#39;rest-api&#39; =&gt; [  <br>        App\Providers\RestApiAppServiceProvider::class,<br>        App\Services\JWTAuth\JWTAuthServiceProvider::class,<br>        /etc.<br>    ],  <br><br>    &#39;monolith&#39; =&gt; [<br>        App\Providers\AppServiceProvider::class,<br>        Collective\Html\HtmlServiceProvider::class,<br>        App\Providers\DebugBarCollectorServiceProvider::class,<br>        App\Providers\CMSServiceProvider::class,<br>        // etc.<br>    ],  <br>],</pre><p>This setup lets us:</p><ul><li>Load specific service providers per application.</li><li>Enable separate global features, such as a stricter Eloquent mode for the REST API (Model::shouldBeStrict(!$this-&gt;app-&gt;isProduction());).</li><li>Optimize performance by excluding unnecessary providers in the REST API.</li></ul><blockquote><strong>Note 1:</strong> To fully achieve this, you need to have a custom application for the non-rest, that will load the contextual providers (similar to what we did with RestApplication).</blockquote><blockquote><strong>Note 2:</strong> To see how you can achieve this with Laravel 11, check the supporting <a href="https://github.com/sunchayn/unorthodox-monoliths-in-laravel">repository</a>. It has all the examples from the article in Laravel 11.</blockquote><h4>1.3. Bonus: Further Optimizations</h4><p><strong>Disable Auto-Discovery<br></strong>Laravel’s package auto-discovery can slow down boot times. Manually registering packages per application can further improve the overall performance of different applications.</p><p>To disable auto-discovery you need to add this to composer.json ,</p><pre>&quot;extra&quot;: {<br>  &quot;laravel&quot;: {<br>      &quot;dont-discover&quot;: [&quot;*&quot;]<br>  }<br>},</pre><p><strong>Per-Application Deployment<br></strong>If your setup allows it, you can deploy and roll back each application independently within the same Laravel codebase. To make your monolith more flexible and reliable, you can configure your load balancer to route requests to different infrastructures based on the request path.</p><p>For example, if a bug appears on the main website and you need to roll back a few releases, a traditional setup might also undo fixes/features for the Rest API. With separate deployments, the Rest API(or any other application) remains unaffected.</p><h3>2. Circuit-Breaker (fuse) for Distributed Databases</h3><p>Large monoliths often mean large databases, multi-region availability, and replication challenges. As traffic grows, the database tends to be the first component to show scalability issues, and at <a href="https://studocu.com/">Studocu</a>, we’ve encountered our share of them. We’ve been using AWS Aurora for a while, and while it solved some issues we had with traditional MySQL, it introduced its own set of problems, most notably, issues with table replication.</p><p>One recurring problem was the loss of large tables during replication. These tables, which store pre-computed data for things like recommendations and popularity, often got lost due to how we synced them. We called this issue the “bricked reader” problem.</p><h4>2.1. Circuit Fuse</h4><p>In typical setups, a <a href="https://martinfowler.com/bliki/CircuitBreaker.html">circuit breaker</a> sits between an implementation and a service, acting as a proxy to manage request availability. In our case, however, the database replication was our main point of failure. Large, frequently synced tables were often lost during replication, but their absence didn’t directly impact the product, it mainly affected SEO-related features like interlinking.</p><p>To avoid taking the entire website down because of a missing meta table, we introduced the concept of a “circuit fuse”. This fuse acts as a software proxy for database interactions that consumes the shock, it detects replication failures and fails gracefully. When a table is missing, it returns an empty state, allowing the UI to adjust accordingly.</p><p>Let’s see how we can build one.</p><p><strong>Step 1: Register a Custom Database Connection</strong></p><p>The first step in implementing a circuit fuse is to override the default MySQL connection class with our custom version. This can be done inside Laravel’s AppServiceProvider (or a dedicated DatabaseServiceProvider) using the Connection::resolverFor() method:</p><pre>use App\Core\Database\Connections\MySqlConnection;<br><br>// AppServiceProvider or DatabaseServiceProvider, etc.<br><br>public function register(): void<br>{<br>    // Register a custom MySQL connection class<br>    Connection::resolverFor(&#39;mysql&#39;, fn (...$args) =&gt; new MySqlConnection(...$args));<br>}</pre><p>This tells Laravel to use MySqlConnection (our custom database connection class) instead of the default MySQL connection whenever a MySQL database connection is used. Which allows us to intercept database queries and handle failures gracefully.</p><p><strong>Step 2: Extend the MySQL Connection Class</strong></p><p>Next, we define our custom connection class MySqlConnection.</p><p>The custom connection extends the base one, and uses a custom trait (HandlesConnectionErrors), which will handle the database failures in a re-usable way so you can attach it to other connections.</p><pre>&lt;?php<br><br>namespace App\Core\Database\Connections;  <br>  <br>use App\Core\Database\Concerns\HandlesConnectionErrors;<br>use Illuminate\Database\MySqlConnection as BaseConnection;<br>  <br>class MySqlConnection extends BaseConnection  <br>{  <br>    use HandlesConnectionErrors;<br>}</pre><p><strong>Step 3: Handle Database Errors Gracefully</strong></p><p>Inside the HandlesConnectionErrors trait, we override the select() method to catch query exceptions and handle them based on the error code.</p><pre>&lt;?php<br><br>trait HandlesConnectionErrors {<br>    public function select($query, $bindings = [], $useReadPdo = true): array  <br>    {  <br>        try {  <br>            return parent::select($query, $bindings, $useReadPdo);  <br>        } catch (QueryException $exception) {  <br>            if (!app()-&gt;isProduction()) {<br>                throw $exception;  <br>            }  <br><br>            /**  <br>             * @see https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html  <br>             */        <br>            return match ($exception-&gt;errorInfo[1] ?? null) {  <br>                1051, // Bad table  <br>                1146, // No such table  <br>                1109, // Unknown table  <br>                1356  // Invalid View or view permission issue  <br>                    =&gt; $this-&gt;failGracefully($exception), <br>                default =&gt; throw $exception,  <br>            };  <br>        } <br>    }<br><br>   private function failGracefully(QueryException $exception): array  <br>   {    <br>       Log::info(&#39;A table was not readable&#39;, context: [  <br>        &#39;sql&#39; =&gt; $exception-&gt;getSql(),  <br>        &#39;error&#39; =&gt; $exception-&gt;getMessage(),  <br>       ]);<br>     <br>       return [];  <br>   }</pre><p><strong>What it does:</strong></p><ul><li>It overrides Laravel’s default select() method to catch query exceptions.</li><li>If the database error is related to a missing table, it returns an <strong>empty array</strong> instead of crashing, allowing the UI to handle the missing data gracefully.</li><li>It logs the error so developers can track issues without affecting users.</li></ul><blockquote><strong>Note</strong>: The example above is tailored for MySQL server errors. Check the supporting <a href="https://github.com/sunchayn/unorthodox-monoliths-in-laravel">repository</a> to see a more elaborate matching that includes another driver, SQLite.</blockquote><h4><strong>2.2. Bonus: Handling Maintenance Failures Gracefully</strong></h4><p>During maintenance tasks (like a blue/green deployment or failover) outside a maintenance mode, the database might be expectedly unavailable for a brief time. We can catch these errors separately and return a <strong>503 Service Unavailable</strong> response:</p><pre>@@ public function select($query, $bindings = [], $useReadPdo = true): array<br>    [..]<br><br>    return match ($exception-&gt;errorInfo[1] ?? null) {  <br>        1051, // Bad table  <br>        1146, // No such table  <br>        1109, // Unknown table  <br>        1356  // Invalid View or view permission issue  <br>            =&gt; $this-&gt;failGracefully($exception),<br>+       2002, // Operation timed out (failover, blue/green switch)  <br>+       1290 // Database has an option preventing statement execution, like `readonly` mode  <br>+            =&gt; $this-&gt;failMaintenenaceErrorGracefully($exception),<br>        default =&gt; throw $exception,  <br>    };</pre><p>The method that handles the errors might look like this,</p><pre>private function failMaintenenaceErrorGracefully(QueryException $exception): never  <br>{  <br>    // Report each exception<br>    // Optionally, implement throttling to report only if the error persists after X seconds.<br>    report($exception);<br>  <br>    abort(  <br>        response(<br>            view(&#39;errors.503&#39;, [&#39;title&#39; =&gt; trans(&#39;messages.website_under_maintenance&#39;)]),  <br>            503,  <br>            [  <br>                &#39;Refresh&#39; =&gt; config(&#39;app.maintenance.refresh&#39;),  <br>            ],<br>        ),  <br>    );  <br>}</pre><h4>2.3. Real Circuit Breaker</h4><p>While the circuit fuse works well for internal systems like the database, it’s not enough when dealing with external services or third-party APIs. In these cases, a true <strong>circuit breaker</strong> is the right call.</p><p>I won’t go into the implementation details here, to avoid being too orthodox, but I recommend the <a href="https://github.com/ackintosh/ganesha">Ganesha PHP</a> package for those looking for a simple solution. You can use it directly or wrap it with your logic to integrate it into your application.</p><h3>3. Hybrid Optimizations When MySQL Alone Isn’t Enough</h3><p>As established in the previous section, the database is often the first component to struggle under increased traffic. Weak database designs and the lack of proper indices are the usual culprits.</p><p>Often, adding the missing index or optimizing queries to use the right indices can solve the problem. However, sometimes you encounter blockers, such as:</p><ul><li><strong>Locking issues</strong> when adding an index to a large table (which can cause downtime).</li><li><strong>Technical limitations</strong> that prevent further optimization.</li></ul><p>When this happens, it helps to think outside the box, literally, and use a combination of PHP + SQL to optimize queries and improve performance.</p><p>Let’s have a practical example, and see how this technique can solve it.</p><h4>3.1. The Problem: Paginating Course Documents by Category</h4><p>We have a course page that displays paginated documents per category. The categories are dynamic, meaning they depend on what documents are available for a course.</p><p><strong>SEO Requirements:</strong></p><ul><li>The first two pages of documents for each category should be pre-loaded during SSR (Server-Side Rendering).</li><li>This makes pagination tricky since we need to paginate per category and load multiple pages in one go.</li></ul><p><strong>Why is MySQL Alone Not Enough?</strong></p><ol><li>LIMIT in subqueries is not allowed, so we’d need a UNION query to handle every possible category.</li><li>Counting all results per category for pagination would require many COUNT() queries, making it inefficient.</li></ol><p><strong>Goal: Load Two Pages Per Category as Fast as Possible</strong></p><p>We want to achieve this with a few queries while ensuring fast execution times.</p><h4>3.2. Solution: Using an Index-Only Query</h4><p>An index-only query retrieves results without accessing the full table, making it almost instantaneous.</p><p>Gladly, for this page, all the information we needed to find the first two pages of valid documents per category with the default sorting are all present in a composite index on the following columns: [course_id, category_id, published_at, deleted_at, popularity_score].</p><p>This means we can:</p><ul><li>Load all documents for a course using an index-only query.</li><li>Group, sort, paginate, and extract metadata in PHP.</li><li>Fetch full document details (for the initial pages) in a second query.</li></ul><h4>Implementation Steps</h4><p>We’ll build a Query class to handle this in three steps:</p><ol><li>Extract metadata per category using an index-only query.</li><li>Load the full document data for selected IDs.</li><li>Hydrate metadata by mapping documents back to their categories.</li></ol><blockquote>In case you are interested on what Query classes are, they were discussed in a previous article: <a href="https://medium.com/studocu-techblog/you-might-not-need-a-repository-in-laravel-3-alternatives-c241638a3922">You might not need a repository in Laravel: 3 alternatives</a>)</blockquote><p>—</p><p>The Query class skeleton:</p><pre>&lt;?php<br><br>class CourseInitialDocumentPerCategoryQuery  <br>{  <br>    public const PER_PAGE = 8;<br>  <br>    private readonly int $totalPerCategory;  <br>  <br>    public function __construct(  <br>        private readonly Course $course,  <br>        private readonly int $perPage = self::PER_PAGE,  <br>    ) {  <br>        $this-&gt;totalPerCategory = $this-&gt;perPage * 2;  // Load two pages per category<br>    }<br><br>    public function get(): Collection  <br>    {  <br>        $metadata = $this-&gt;getMetadataPerCategory();<br>  <br>        $documentsById = $this<br>          -&gt;loadDocumentsFromIds(<br>              ids: $metadata-&gt;flatMap-&gt;items-&gt;pluck(&#39;id&#39;)-&gt;all(),<br>          )<br>          -&gt;keyBy(&#39;id&#39;);<br><br>        $documents = $this-&gt;metadataToPaginatedCategories($metadata, $documentsById);<br>  <br>        // you might also eager load the documents&#39; relations.<br>  <br>        return $documents;  <br>    }<br>}</pre><p><strong>Step 1: Extract metadata per category using an index-only query</strong></p><p>In this step, we leverage an index-only query to retrieve document metadata quickly. With this metadata, we can find the first two pages of documents per category (after sorting) plus the total number of documents which is information needed for length-aware pagination.</p><pre><br>private function getMetadataPerCategory(): Collection  <br>{  <br>    return Document::query() <br>      -&gt;select(&#39;id&#39;, &#39;category_id&#39;, &#39;popularity_score&#39;, &#39;published_at&#39;)  <br>      -&gt;where(&#39;course_id&#39;, $this-&gt;course-&gt;id)  <br>      -&gt;whereNotNull(&#39;published_at&#39;)<br>      -&gt;toBase() // &lt;- Avoids Eloquent hydration <br>      -&gt;get() // &lt;- Fetches ALL assigned documents for the course  <br>      -&gt;groupBy(&#39;category_id&#39;)  <br>      -&gt;map(fn (Collection $documents): array =&gt; [  <br>          &#39;total&#39; =&gt; $documents-&gt;count(),  <br>          &#39;items&#39; =&gt; $this-&gt;rearrangeDocumentsOnPages($documents),<br>      ]);<br>}<br><br>private function rearrangeDocumentsOnPages(Collection $documentsMetadata): Collection  <br>{  <br>    return $documentsMetadata  <br>        -&gt;sortBy([  <br>            [&#39;popularity_score&#39;, &#39;desc&#39;],  <br>            [&#39;published_at&#39;, &#39;desc&#39;],  <br>            [&#39;id&#39;, &#39;desc&#39;],  <br>        ])  <br>        -&gt;take($this-&gt;totalPerCategory);  // Keep only two pages worth of documents<br>}</pre><p><strong>Step 2: Load Full Document Data</strong></p><p>After gathering the metadata, we can now proceed to load the full documents based on the IDs we collected. This is done with a single query that selects only the necessary fields for display.</p><pre>private function loadDocumentsFromIds(array $ids): Collection  <br>{<br>    return Document::query()  <br>      -&gt;select([  <br>          // Required columns<br>      ])<br>      -&gt;whereIntegerInRaw(&#39;id&#39;, $ids)<br>      -&gt;get();<br>}</pre><p><strong>Step 3: Hydrate Metadata with Full Documents</strong></p><p>We map the full documents back to the metadata, ensuring the correct order. We also calculate pagination-related metadata like the current page and total pages based on the document count per category.</p><pre>private function metadataToPaginatedCategories(Collection $metadata, Collection $documentsById): Collection  <br>{<br>    return $metadata  <br>      -&gt;map(fn (array $categoryMetadata, int $categoryId) =&gt; [<br>          &#39;items&#39; =&gt; EloquentCollection::make(<br>              $categoryMetadata[&#39;items&#39;]<br>                  -&gt;map(fn (object $rawDocumentObject): Document =&gt; $documentsById-&gt;get($rawDocumentObject-&gt;id))<br>                  -&gt;values(),<br>          ),<br>         &#39;metadata&#39; =&gt; [<br>             &#39;total&#39; =&gt; $categoryMetadata[&#39;total&#39;],<br>             &#39;per_page&#39; =&gt; ...,<br>             &#39;current_page&#39; =&gt; ...,<br>             &#39;last_page&#39; =&gt; ...,<br>          ],<br>      ]);<br>}</pre><h4>3.3. The Results</h4><p>With the above technique, we’ve achieved our goal with just 2 queries (not counting the eager loading) and massively optimized the page.</p><p>The courses with a large document pool went from ~8s to &lt;200ms. The ones with a small document pool went from ~200ms to &lt;34ms. Plus, the total number of queries on the page went from 58 to 24. These are amazing numbers for what we had originally.</p><blockquote><strong>Are you struggling with your database?</strong></blockquote><blockquote>In case you are in the stage already and adding indices is not helping, make sure to consider reading this book &lt;<a href="https://sqlfordevs.com/ebooks/indexing">Indexing Beyond The Basics</a>&gt;. It will be a massive help for your query optimization journey.</blockquote><h3>Closing Notes</h3><p>This article explored different strategies for addressing scalability/maintainability challenges in large monoliths. We covered multi-application infrastructure to separate code per application, circuit fuses for more reliable databases, and index-only queries to handle complex data requirements. Keep in mind that what works for one system may not be the best for another, so adapting these approaches to fit your specific needs is important. Happy optimizing!</p><p>Check out this <a href="https://github.com/sunchayn/unorthodox-monoliths-in-laravel">repository</a> that has examples for everything discussed in this article (adjusted for Laravel 11).</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebb41277780e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/studocu-techblog/unorthodox-monoliths-in-laravel-ebb41277780e">Unorthodox Monoliths in Laravel</a> was originally published in <a href="https://medium.com/studocu-techblog">Studocu Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cacheable Entities: A Laravel package with a story]]></title>
            <link>https://medium.com/studocu-techblog/cacheable-entities-a-laravel-package-with-a-story-239a8bfc8043?source=rss-7928fab44e3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/239a8bfc8043</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mazen Touati]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 13:22:02 GMT</pubDate>
            <atom:updated>2026-07-12T23:47:00.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaling Laravel Cache: A Standardized Architecture for High-Traffic Applications</h3><p>At <a href="https://studocu.com/">Studocu</a>, we handle hundreds of millions of records and support 2 million daily active users (around 60 million monthly users). At this scale, every millisecond of a user’s request is critical. In the early days, we started with a standard cache-aside strategy using Redis as our main cache store.</p><p>As <a href="https://studocu.com/">Studocu</a> grew from a small team and a simple codebase into one of the top 750 most visited websites globally, scaling our infrastructure introduced new challenges. One major hurdle was caching retrieved database records efficiently and maintaining code simplicity. This article shares how we designed a standardized caching system to ensure performance and maintainability at scale.</p><p>With more teams and features, we accumulated legacy practices. We ended up with conflicting caching strategies, scattered cache keys, and a lack of clarity on caching patterns. To address this, we analyzed our existing caching patterns and designed a standardized approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnT4vSownaljDAKIDxiPcA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mazerone?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Simone Pellegrini</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-large-green-leaf-ES3lCi0VNDQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>—</p><p>After reading this article, you will:</p><ul><li>Gain insights into the challenges we encountered amid a rapidly expanding codebase and company.</li><li>Explore the cacheable entities: An opinionated infrastructure for standardized caching.</li><li>Leverage cacheable entities for the “stale cache” technique to further optimize response times.</li><li>Discover the art of serializing/deserializing cache values to significantly trim down cache sizes.</li></ul><h3>The Problems We Faced</h3><p>Before we jump into the solution, let’s talk about the issues we were dealing with:</p><ul><li><strong>Scattered Cache Keys and TTLs:</strong> Cache keys and TTLs were hardcoded across multiple controllers, event listeners, and tests. Modifying a key or TTL required manual updates in multiple places, which was error-prone.</li><li><strong>Inconsistent Real-time Value Retrieval:</strong> It was unclear how to bypass the cache to retrieve fresh, real-time data when needed, leading to inconsistent workarounds.</li><li><strong>Asynchronous Updates:</strong> Managing asynchronous cache refreshes lacked a standardized pattern, leading developers to implement custom, ad-hoc solutions.</li><li><strong>Serialization and Deserialization:</strong> The serialization and deserialization of cached data was handled inconsistently, increasing complexity and cache sizes.</li></ul><p>Addressing these issues allowed us to establish a clean and standardized cache-aside implementation.</p><h3>What We Needed</h3><p>As mentioned earlier, we’ve been interacting with the cache infrastructure directly in our application code. These separate parts of the codebase had to know the TTL and the cache key themselves.</p><p>We had two primary areas to address:</p><p><em>Key and TTL Management:</em></p><ul><li>Crafting cache keys.</li><li>TTL encapsulation.</li></ul><p><em>Caching and Accessing Cacheable Values:</em></p><ul><li>Dealing with the same cacheable values using varied caching strategies (more on this below).</li><li>Making the process of serializing and deserializing cached values more straightforward.</li></ul><p>These needs defined our goals for a new, standardized caching library.</p><p><strong>Our Approach to Caching</strong></p><p>In our scenario, we navigated between two distinct caching strategies: Blocking and Non-blocking cache.</p><ul><li><strong>Blocking Cache (Synchronous):</strong> If we don’t have the value, we compute it, cache it, and serve up the result right away.</li><li><strong>Non-blocking Cache (Asynchronous):</strong> If we don’t have the value, we dispatch a job to compute it, and return an empty state (like null, empty collection, or an empty array).</li></ul><p>Every cacheable value had to support both strategies. Depending on the context, the same entity might be cached or accessed using either a synchronous or asynchronous approach. For instance, a web request might load a non-blocking stale state to keep response times low, whereas a background API request could use the blocking strategy to ensure the latest data is retrieved.</p><h3>The solution: a.k.a Cacheable Entities</h3><p>To standardize caching, we developed an opinionated library called “Cacheable Entities.” This library provides an abstraction layer that isolates cache logic from application code.</p><p>The library is open-source and available in the <a href="https://github.com/StuDocu/cacheable-entities">Cacheable Entities repository</a>. Below, we explain how to integrate and use it.</p><h3>Defining a cacheable entity</h3><p>To make a class cacheable entity it has to implement the StuDocu\CacheableEntities\Contracts\Cacheable contract.</p><p>The interface implementation requires defining the following methods:</p><ul><li><strong>getCacheTTL:</strong> Returns the TTL of the cache in seconds.</li><li><strong>getCacheKey:</strong> Returns the cache key.</li><li><strong>get:</strong> Computes the Entity value to be cached.</li></ul><h3>Reading the value of a cacheable entity</h3><p>Using the two caching strategies, mentioned above, with Cacheable Entities is made easy thanks to the two available utility classes: SyncCache and AsyncCache</p><ul><li>StuDocu\CacheableEntities\SyncCache@get: Accepts a cacheable entity and will wait and cache the result if not pre-cached yet. Then returns the value.</li><li>StuDocu\CacheableEntities\AsyncCache@get: Accepts a cacheable entity and will return the cached value if it is a cache hit. Otherwise, it will dispatch a job to compute the cache value asynchronously and then return an empty</li></ul><p><strong>Example</strong></p><pre>&lt;?php<br><br>use App\Models\Author;<br>use App\Models\Book;<br>use Illuminate\Database\Eloquent\Collection;<br>use StuDocu\CacheableEntities\Contracts\Cacheable;<br><br>/**<br> * @phpstan-type ReturnStructure Collection&lt;int, Book&gt;<br> *php<br> * @implements Cacheable&lt;ReturnStructure&gt;<br> */<br>class AuthorPopularBooksQuery implements Cacheable, SerializableCacheable<br>{<br>    public const DEFAULT_LIMIT = 8;<br><br>    public function __construct(<br>        protected readonly Author $author,<br>        protected readonly int $limit = self::DEFAULT_LIMIT,<br>    ) {<br>    }<br><br>    public function getCacheTTL(): int<br>    {<br>        return 3600 * 24;<br>    }<br><br>    public function getCacheKey(): string<br>    {<br>        return &quot;authors:{$this-&gt;author-&gt;id}:books:popular.v1&quot;;<br>    }<br><br>    public function get(): Collection<br>    {<br>        return Book::query()<br>            -&gt;join(&#39;book_popularity_scores&#39;, &#39;book_popularity_scores.book_id&#39;, &#39;=&#39;, &#39;books.id&#39;)<br>            -&gt;where(&#39;author_id&#39;, $this-&gt;author-&gt;id)<br>            -&gt;whereValid()<br>            -&gt;whereHas(&#39;ratings&#39;)<br>            -&gt;orderByDesc(&#39;document_popularity_scores.score&#39;)<br>            -&gt;take($this-&gt;limit)<br>            -&gt;get();<br>    }<br>}<br><br>// Usage<br><br>$query = new AuthorPopularBooksQuery($author);<br><br>// Get a non-blocking cache result in the web endpoint.<br>resolve(\StuDocu\CacheableEntities\AsyncCache::class)-&gt;get($query);<br><br>// Get a blocking cache result in the API endpoint.<br>resolve(\StuDocu\CacheableEntities\SyncCache::class)-&gt;get($query);</pre><h3>Serialization/Deserialization</h3><p>Serializable cache works by providing a behind-the-scene layer to the cacheable entity that will handle serializing and deserializing the cache value without the awareness of the client code.</p><h4><strong>Why it is needed</strong></h4><p>This pattern is used in cases where we want to save space. We cache only metadata of the value, say an array of model IDs, later we can fetch the data again from the database. The second time we fetch the data, we will directly get the modes via their IDs. This will be a fast query as we are directly getting what we need, rather than computing what we need (which is what takes time).</p><p>The pros and cons are:</p><ul><li>+ Small cache footprint</li><li>+ It allows excluding no longer valid items from the response (like deleted/deactivated models after they were cached).</li><li>- It doesn’t necessarily reduce the number of DB requests (although it reduces the complexity of the queries).</li></ul><h4><strong>Usage</strong></h4><p>To make a cacheable entity serializable, you will need to implement the following contract StuDocu\CacheableEntities\Contracts\SerializableCacheable.</p><p>The interface implementation requires defining the following methods:</p><ul><li><strong>serialize(mixed $value): mixed</strong>: Prepares the result for the cache. It will be called anytime a cacheable entity is about to be cached. The result of this method will be the cache value.</li><li><strong>unserialize(mixed $value): mixed</strong>: Restores the original state of the cached values. It will be called anytime a cache value is read. The result of this method is what will be returned as the cache value.</li></ul><p><strong>Example,</strong></p><pre>&lt;?php<br><br>// [...]<br><br>use StuDocu\CacheableEntities\Contracts\SerializableCacheable;<br><br>class AuthorPopularBooksQuery implements Cacheable, SerializableCacheable<br>{<br>   // [...]<br><br>   /**<br>    * @param Collection&lt;Book&gt; $value<br>    * @return array&lt;int&gt;<br>    */<br>   public function serialize(mixed $value): array<br>   {<br>       // `$value` represents the computed value of this query; it will be what we will get when calling self::get().<br>       return $value-&gt;pluck(&#39;id&#39;)-&gt;all();<br>   }<br>   <br>    /**<br>     * @param  int[]  $value<br>     * @return  Collection&lt;int, Book&gt;<br>     */<br>    public function unserialize(mixed $value): Collection<br>    {<br>        // `$value` represents what we&#39;ve already cached previously, it will the result of self self::serialize(...)<br>        <br>        $booksFastAccess = array_flip($value);<br>        <br>        $books = Book::query()<br>            -&gt;findMany($value)<br>            -&gt;sortBy(fn (Book $book) =&gt; $booksFastAccess[$book-&gt;id] ?? 999)<br>            -&gt;values();<br>    <br>        $this-&gt;setRelations($books);<br>    <br>        return $books;<br>    }<br>    <br>    /**<br>     * @param  ReturnStructure  $books<br>     */<br>    private function setRelations(Collection $books): void<br>    {<br>        $books-&gt;each-&gt;setRelation(&#39;author&#39;, $this-&gt;author);<br><br>        // Generally speaking, you can do eager loading and such in a similar fashion (for ::get and ::unserialzie).<br>    }<br>}<br><br>// Usage is still unchanged.<br>$query = new AuthorPopularBooksQuery($author);<br><br>// Get a non-blocking cache result in the web endpoint.<br>resolve(\StuDocu\CacheableEntities\AsyncCache::class)-&gt;get($query);<br><br>// Get a blocking cache result in the API endpoint.<br>resolve(\StuDocu\CacheableEntities\SyncCache::class)-&gt;get($query);</pre><p>Given that this query is now an instance of a “serializable cacheable” it will be serialized/unserialized on the fly anytime is read through the SyncCache or AsyncCache utilities. The client code doesn&#39;t have to change, it uses the same API to read the value.</p><blockquote>💡 Thanks to PHP type <a href="https://www.php.net/manual/en/language.oop5.variance.php#language.oop5.variance.covariance">covariance</a> we were able to overwrite the return types of serialize and unserialize from mixed to something more specific.</blockquote><p><strong>Caveat when unserializing</strong></p><p>Depending on how you serialize your models, you might lose the original order when unserializing, e.g. when only caching the IDs.</p><p>For Entities where the order matters. Make sure to retain the original order when unserializing.</p><p>Here are some examples of how to do so,</p><pre>// Retaining the original order with array_search<br>$books = Book::query()<br>    -&gt;findMany($value)<br>    -&gt;sortBy(fn (Book $book) =&gt; array_search($book-&gt;id, $value))<br>    -&gt;values();<br><br>// Retaining the original order with array_flip.<br>// A faster alternative than the above, using direct array access instead of `array_search`.`<br>$booksFastAccess = array_flip($value);<br>$book = Book::query()<br>    -&gt;findMany($value)<br>    -&gt;get()<br>    -&gt;sortBy(fn (Book $book) =&gt; $booksFastAccess[$book-&gt;id] ?? 999)<br>    -&gt;values();<br><br>// Retaining the original order with SQL.<br>$books = Book::query()<br>    -&gt;orderByRaw(DB::raw(&#39;FIELD(id, &#39; . implode(&#39;,&#39;, $value) . &#39;)&#39;))<br>    -&gt;get();</pre><h3>Purging the cache</h3><p>Anytime you want to invalidate the cache value of a cacheable entity, you need to use the SyncCache::forget method.</p><p>The use of SyncCache for this is because the invalidation happens on the spot.</p><p>Here are some examples of how to do so,</p><pre>&lt;?php<br><br>$query = new AuthorPopularBooks($author);<br><br>// Invalidate the cache (for example, in an event listener).<br>resolve(\StuDocu\CacheableEntities\SyncCache::class)-&gt;forget($query);</pre><h3>Async cache default value</h3><p>When using the AsyncCache utility, it will return null on a cache miss. In some cases, you might need to change the default value. All you need to do is make the cacheable entity implement the following interface StuDocu\CacheableEntities\Contracts\SupportDefaultCacheValue</p><p>The interface implementation requires defining the following method:</p><ul><li><strong>getCacheMissValue:</strong> specifies the default value on cache miss (when using the async strategy).</li></ul><p><strong>Example,</strong></p><pre>&lt;?php<br><br>// [...]<br><br>use Illuminate\Database\Eloquent\Collection;<br>use StuDocu\CacheableEntities\Contracts\SupportsDefaultValue;<br><br>class AuthorPopularBooks implements Cacheable, SupportsDefaultValue<br>{<br>   public function getCacheMissValue(): Collection<br>   {<br>      return Collection::empty();<br>   }<br>}</pre><h3>Generic Annotation</h3><p>At Studocu, we use <a href="https://phpstan.org/">PHPStan</a> (via <a href="https://github.com/larastan/larastan">Larastan</a>) for static analysis. Since the return types of our cache utilities are generic, we integrated PHPStan generic type definitions into the Cacheable Entities library. This ensures return types are fully type-safe and validated during static analysis.</p><p>Let’s see what generics are available.</p><ul><li><strong>Cacheable Generic:</strong> This contract accepts one generic definition &lt;TReturn&gt;, which is what the entity will return when calling get to compute its value.</li><li><strong>SerializableCacheable Generic:</strong> This contract accepts two generic definitions &lt;TUnserialized, TSerialized&gt;</li><li>TUnserialized: The type that will be returned when we unserialize the cache value. It should be the same shape as TReturn to ensure consistency.</li><li>TSerialized: the type that will be returned when we serialize the result.</li><li><strong>SupportsDefaultValue Generic:</strong> This contract accepts one generic definition &lt;TDefault&gt;, which is what the entity will return when missing the cache while using the AsyncCache utility. It should be the same shape as TReturn to ensure consistency.</li></ul><p><strong>Example,</strong></p><pre>&lt;?php<br><br>/**<br> * @phpstan-type ReturnStructure Collection&lt;User&gt;<br> * @implements Cacheable&lt;ReturnStructure&gt;<br> * @implements SerializableCacheable&lt;ReturnStructure, int[]&gt;<br> * @implements SupportsDefaultValue&lt;ReturnStructure&gt;<br> */<br>class CourseQuery implements Cacheable, SerializableCacheable, SupportsDefaultValue<br>{}</pre><h3>Noteworthy Improvements</h3><p>Now that we’ve rolled out our standardized caching solution, let’s see how it’s made a difference in practice.</p><h4>Streamlined Developer Experience</h4><p>With our standardized approach in place, developers no longer need to second-guess themselves when it comes to caching. The infrastructure provides a straightforward way to read from and write to the cache, making their lives easier.</p><p>Also, it promoted more visibility and knowledge about what you might and might not cache and possible ways to access it.</p><h4>Turbocharging Performance with Async Cache</h4><p>We also used the asynchronous strategy to implement a stale cache technique for slow queries. When a value is computed, the library saves it in the cache with an extended TTL. When retrieving this value asynchronously, a cache miss prompts the library to return the stale data immediately while dispatching a background job to compute the fresh value and update the cache. This prevents user-facing requests from blocking on heavy database operations, which significantly reduces load times on complex pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7QiWZoQQEcTeebGW0CFpg.png" /><figcaption>Stale cache technique performance boost (values are in Nanoseconds).</figcaption></figure><p><strong>Note:</strong> This technique is a secondary optimization; query optimization remains the primary goal. If legacy database structures or technical limitations prevent further optimization, the stale cache pattern serves as an effective intermediate solution to keep response times low.</p><p><strong>Example,</strong></p><pre>&lt;?php<br><br>use App\Models\Author;<br>use App\Models\Book;<br>use Illuminate\Database\Eloquent\Collection;<br>use StuDocu\CacheableEntities\Contracts\Cacheable;<br>use StuDocu\CacheableEntities\Contracts\SupportsDefaultValue;<br><br>/**<br> * @phpstan-type ReturnStructure Collection&lt;int, Book&gt;<br> *<br> * @implements Cacheable&lt;ReturnStructure&gt;<br> * @implements SupportsDefaultValue&lt;ReturnStructure&gt;<br> */<br>class AuthorPopularBooksWithStaleCacheQuery implements Cacheable, SupportsDefaultValue<br>{<br>    public const DEFAULT_LIMIT = 8;<br><br>    public function __construct(<br>        protected readonly Author $author,<br>        protected readonly int $limit = self::DEFAULT_LIMIT,<br>    ) {<br>    }<br><br>    public function getCacheTTL(): int<br>    {<br>        return 3600 * 24;<br>    }<br><br>    public function getCacheKey(): string<br>    {<br>        return &quot;authors:{$this-&gt;author-&gt;id}:books:popular.v1&quot;;<br>    }<br><br>    public function get(): Collection<br>    {<br>        $books = Book::query()<br>            -&gt;join(&#39;book_popularity_scores&#39;, &#39;book_popularity_scores.book_id&#39;, &#39;=&#39;, &#39;books.id&#39;)<br>            -&gt;where(&#39;author_id&#39;, $this-&gt;author-&gt;id)<br>            -&gt;whereValid()<br>            -&gt;whereHas(&#39;ratings&#39;)<br>            -&gt;orderByDesc(&#39;document_popularity_scores.score&#39;)<br>            -&gt;take($this-&gt;limit)<br>            -&gt;get();<br><br>        $this-&gt;setRelations($books);<br><br>        return tap(<br>            $books,<br>            function (Collection $results) {<br>                cache()-&gt;put(<br>                    $this-&gt;getStaleCacheKey(),<br>                    $results,<br>                    $this-&gt;getStaleCacheTTL(),<br>                );<br>            },<br>        );<br>    }<br><br>    private function getStaleCacheKey(): string<br>    {<br>        return $this-&gt;getCacheKey() . &#39;:stale&#39;;<br>    }<br><br>    private function getStaleCacheTTL(): int<br>    {<br>        return $this-&gt;getCacheTTL() + (3600 * 24);<br>    }<br><br>    public function getCacheMissValue(): Collection<br>    {<br>        $books = cache()-&gt;get($this-&gt;getStaleCacheKey(), Collection::empty());<br><br>        if (! ($books instanceof Collection) || $books-&gt;isEmpty()) {<br>            // When we neither have the up-to-date results nor the stale results cached, we compute<br>            // them synchronously as a last resort.<br>            return $this-&gt;get();<br><br>            // Or you can return an empty collection if you don&#39;t want to have a value every time.<br>        }<br><br>        return $books;<br>    }<br><br>    /**<br>     * @param  ReturnStructure  $books<br>     */<br>    private function setRelations(Collection $books): void<br>    {<br>        $books-&gt;each-&gt;setRelation(&#39;author&#39;, $this-&gt;author);<br><br>        // Generally speaking, you can do eager loading and such in a similar fashion (for ::get and ::unserialize).<br>    }<br>}</pre><p><strong>Some caveats of this approach:</strong></p><ul><li>We are treating an otherwise blocking value as a non-blocking value which might not feel natural.</li><li>On cache miss for both original and stale caches, we will compute the value on-the-fly which will be an exceptionally slow request (for that user).</li></ul><h4>Shrinking Cache Size with Serialization</h4><p>By implementing the SerializableCacheable contract, we reduced the cache footprint of our models by caching only the primary keys (IDs). This modification reduced our largest cached Redis key size by 97.17%, freeing memory and allowing more keys to be retained. We have since applied this strategy to other large cached objects.</p><p>Reducing cache sizes is particularly important when using eviction policies like Least Recently Used (LRU). A smaller footprint prevents premature eviction of active cache keys when memory limits are reached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hC_gA6ODclSJRRWW0fICug.png" /><figcaption>Cache share distribution before and after migrating the largest key in the cache (in orange)</figcaption></figure><h3>Conclusion</h3><p>Establishing clear caching standards ensures consistency as engineering teams grow. Standardized caching is essential for managing large-scale databases and high-traffic applications. However, caching is not a replacement for query optimization. Database queries should always be optimized before implementing a caching layer.</p><p>If you have feedback or suggestions for the package, feel free to open an issue or pull request on the repository.</p><p>Curious about the Query classes we touched upon? Dive deeper into their usage at Studocu:</p><p><a href="https://medium.com/studocu-techblog/you-might-not-need-a-repository-in-laravel-3-alternatives-c241638a3922">You might not need a repository in Laravel: 3 alternatives</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=239a8bfc8043" width="1" height="1" alt=""><hr><p><a href="https://medium.com/studocu-techblog/cacheable-entities-a-laravel-package-with-a-story-239a8bfc8043">Cacheable Entities: A Laravel package with a story</a> was originally published in <a href="https://medium.com/studocu-techblog">Studocu Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[20 practical productivity tips that you can start doing today as a developer (no Pomodoro)]]></title>
            <link>https://medium.com/studocu-techblog/20-practical-productivity-tips-that-you-can-start-doing-today-as-a-developer-no-pomodoro-b45766724f51?source=rss-7928fab44e3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b45766724f51</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Mazen Touati]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 12:24:58 GMT</pubDate>
            <atom:updated>2023-09-22T11:34:42.858Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ve curated practical and straightforward tips for enhancing your productivity as a developer (some are applicable to non-developers too), which I use daily.</p><p>I’ve organized these tips into the following four themes for an easy reference:</p><ul><li>Level up your working environment.</li><li>Optimize your coding workflow.</li><li>Make your debugging resourceful.</li><li>Work on your soft skills.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9VIEEKJwUfRqIvQs_QtIg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@erol?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Erol Ahmed</a> on <a href="https://unsplash.com/photos/aIYFR0vbADk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>—</p><h3>Level up your working environment</h3><h4>1. Choose the Right Theme</h4><p>While this may seem unconventional for such an article, selecting the right theme plays a crucial role in your productivity. Many developers default to dark themes for their favorite IDEs, often arguing they’re easier on the eyes. However, this belief is perhaps <a href="https://www.allaboutvision.com/digital-eye-strain/is-dark-mode-better-for-eyes/#:~:text=Using%20dark%20mode%20is%20helpful,to%20focus%20on%20the%20screen.">not universal across scientists</a>. Personally, I find dark themes uncomfortable, causing text to appear blurry. If you share the same experience, consider giving lighter themes a try. Dimmed themes like <a href="https://ethanschoonover.com/solarized/"><em>Solarized</em></a> are an excellent option as well.</p><p><strong>Why does theme choice matter for productivity?</strong></p><p>A theme that strains your eyes can reduce your focus and, by extension, your efficiency. Prioritize your eye comfort for a better coding experience and overall well-being.</p><blockquote>💡 Read more about cognitive load at <a href="https://stitcher.io/blog/a-programmers-cognitive-load">A programmers cognitive load</a></blockquote><h4>2. Master Shortcuts</h4><p>To get started, explore the available shortcuts in your IDE’s settings, typically found under theKeymap option. However, for a more proactive approach, consider using plugins like <a href="https://plugins.jetbrains.com/plugin/9792-key-promoter-x"><strong>Key Promoter</strong></a>. This tool not only helps you remember existing shortcuts for manual tasks but also suggests creating shortcuts for actions without a shortcut assigned to them yet.</p><p>Here are some things you might consider looking into,</p><ul><li>Utilize caret manipulation shortcuts for tasks like selection, deletion, and navigation between words and lines, applicable not just in your IDE but also in all text inputs, including the terminal.</li><li>Swap and duplicate lines.</li><li>Access clipboard history.</li><li>Jump to a line, Jump to a file, and jump to a line in a file.</li><li>Access the refactoring options (especially for JetBrains products).</li><li>Toggle the file tree display.</li><li>Etc.</li></ul><blockquote>💡 <strong>Are you using PhpStorm?</strong></blockquote><blockquote>If you’re a PhpStorm user, there’s a lot you can do to make it less overwhelming. The following is a personal recommendation for setting an opinionated <a href="https://www.youtube.com/watch?v=jVTk-F3g9XM">minimalistic PhpStorm setup</a>. You can cherry-pick what resonates with you.</blockquote><p>Are you interested in knowing more about IDE shortcuts? Check out this article by <a href="https://medium.com/@ksntcrq"><strong>Killian Saint Cricq</strong></a><strong>.</strong></p><p><a href="https://medium.com/studocu-techblog/5-shortcuts-i-wish-i-knew-when-i-started-using-an-ide-e16525d08146">5 shortcuts I wish I knew when I started using an IDE</a></p><h4>3. Upgrade Your Hardware</h4><p>If you rely solely on your laptop’s keyboard and trackpad, including the magic trackpad, it might be worth considering switching to an external keyboard and mouse. While it might take some adjustment, the return on investment is substantial. This change will unlock greater flexibility and precision when navigating your codebase. You can still replicate most trackpad gestures using keyboard shortcuts (in case you’re worried about that).</p><p>Here are some mouse recommendations:</p><ul><li>Prioritize an ergonomic design that fits your hand comfortably.</li><li>Opt for a mouse with at least the navigation buttons (prev and next), which greatly aids code navigation.</li></ul><p>I understand that this advice might come across as condescending, and you may already feel efficient with your current setup. Not to worry, we still have plenty of other tips that are less opinionated.</p><h4>4. Consider Focusing Your View</h4><p>Many developers opt for multiple screens, multi-view terminals, etc. However, it’s highly unlikely that you need to monitor all these sources simultaneously at all times. Human cognitive load has its limits. Unless you’re dealing with an exceptionally complex scenario that requires aggregating multiple information sources, it may be more productive to narrow down your focus.</p><p>You can explore alternatives such as using closed-display mode or naming terminal tabs for a more streamlined workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*GV2_mwif-tx6qJyQX8Wr3Q.png" /><figcaption>Named terminal tabs example</figcaption></figure><h3>Optimize your coding workflow</h3><h4>5. Learn Regex</h4><p>I can’t emphasize this enough: Regular expressions (Regex) are an incredibly potent tool for refactoring and searching. I understand they can be challenging to master and remember entirely, but you don’t need to remember everything by heart. What’s crucial is understanding concepts, like grouping, lookahead, and lookbehind. After that, it’s perfectly fine to search for the syntax whenever you need it.</p><p>Your regular expressions don’t have to be perfect or designed for long-term maintainability. They can be as hacky as needed to get the job done for a specific task at hand.</p><blockquote>Are you struggling with Regex? Laracast has a great series &lt;<a href="https://laracasts.com/series/understanding-regular-expressions"><strong>Understand Regular Expressions</strong></a><strong>&gt; </strong>that can help you out.</blockquote><h4>6. Probably you don’t need a browser</h4><p>This advice primarily applies to back-end developers. In many instances, you can efficiently develop features without the need to interact directly with your browser. You can accomplish this by relying solely on automated tests. This is where things like <a href="https://en.wikipedia.org/wiki/Test-driven_development"><strong>Test-Driven Development (TDD)</strong></a> are very handy. While it may initially slow down development, it ultimately saves time when addressing bugs, introducing new features, and making changes after receiving QA feedback.</p><p>With a well-tested backend, you can confidently make modifications without the tedious process of manual testing to ensure nothing is accidentally broken.</p><h4>7. Have Faith in Your Tests and Your QA Engineer</h4><p>This complements the previous tip. When you’ve crafted robust feature tests (or their equivalents in your ecosystem), manual clicking around becomes largely unnecessary. As long as your tests are conclusive, you’re on the right track.</p><p>Consider incorporating <a href="https://en.wikipedia.org/wiki/Mutation_testing"><strong>Mutation Testing</strong></a> into your workflow if you haven’t already. This practice helps pinpoint inconclusive tests and enhances your ability to identify additional scenarios that might require testing in your code.</p><blockquote>💡 <strong>Disclaimer</strong></blockquote><blockquote>This doesn’t imply blindly pushing code to production. It simply means avoiding time-consuming tasks that can be automated through testing or validated in separate processes, such as the QA phase.</blockquote><h4>8. Prioritize Results First, Refactor Later</h4><p>This concept goes hand in hand with TDD. The idea is that it’s way faster to achieve results first and then refactor the code later. Don’t make it perfect on the first try. Once you have the full picture of your code and it is thoroughly tested, you can readily optimize it by removing redundancy (DRY-ing it up) and making it more modular and maintainable.</p><h4>9. You Might Not Need The Documentation</h4><p>The title may seem clickbaity, but the concept here is that there are times when it’s more effective (and beneficial) to dive into the vendor method’s definition to comprehend its functionality. This approach offers two significant advantages in my experience:</p><ul><li>It allows for a deep understanding of how that piece of code functions.</li><li>It can lead to the discovery of low-level helpers and techniques that are typically undocumented.</li></ul><p>So, it’s not just about understanding what a method does; it’s also an opportunity to learn something new. Countless times, I’ve gained insights into new low-level helpers, techniques, and approaches simply by examining the source code.</p><h4>10. Take Breaks</h4><p>Frequently, we find ourselves staring at the screen, grappling with complex features or tackling stubborn bugs. Over time, this can become frustrating, and sometimes the most effective solution is to simply take a break. You can divert your attention to tasks like PR reviews or spec writing, or even step away for a walk, prepare a coffee, or briefly gaze out the window. The key is to return to your problem with a fresh mindset, which may provide a different perspective and help smooth the process.</p><p>This approach resembles the <a href="https://en.wikipedia.org/wiki/Pomodoro_Technique"><strong>Pomodoro Technique</strong></a> but without the rigidly predefined timeframes that can occasionally disrupt your productive flow.</p><h4>11. Leverage GitHub’s Online Editor</h4><p>For those hosting their repositories on GitHub, then you can take advantage of the online VSCode editor at <a href="http://github.dev/"><strong>github.dev</strong></a><strong>.</strong> This can help with PR reviews (including leaving comments, suggestions, etc.) and small commits without switching branches locally.</p><p>You can simply modify the PR’s URL from <a href="http://github.com/"><strong>github.com</strong></a> to <a href="http://github.dev/"><strong>github.dev</strong></a>, or press <strong>.</strong> while on the PR to access the online IDE directly.</p><h3>Make your debugging resourceful</h3><h4>12. Debug Your Queries Sooner</h4><p>When working with an ORM, handling complex SQL queries may not always be straightforward. When you encounter issues such as test failures or unexpected behavior while working on a feature, begin by examining what the ORM is generating behind the scenes. Verify that the generated query aligns with what should be executed.</p><h4>13. Master Your Error Messages</h4><p>Sadly, not all errors come with clear explanations, especially those originating in low-level vendor code. Therefore, it’s crucial to invest extra effort in comprehending the error and its underlying cause.</p><p>The next time you encounter a similar error, you should promptly recognize the root cause or what might help understand it. This proactive approach can save you valuable time in troubleshooting and resolving issues.</p><h4>14. Transform Each Debug Session Into a Learning Opportunity</h4><p>Stay vigilant about anything that slows down your progress, and be sure to transform your debugging experiences into valuable learning opportunities. So you can adapt your debugging strategies to what you missed the last time.</p><p>For instance:</p><p>Imagine you’re a Laravel developer who’s invested a significant amount of time debugging deep-nested code that produced puzzling results. You eventually discovered that Eloquent’s default behavior is to return <strong>null</strong> for unselected attributes in the query. The next time you find yourself in a complex debugging session involving Eloquent, consider temporarily enabling <a href="https://laravel.com/docs/10.x/eloquent#configuring-eloquent-strictness"><strong>Eloquent strict mode</strong></a>. This kind of adaptability in your debugging strategies can help you avoid similar pitfalls in the future.</p><h3>Work on your soft-skills</h3><h4>15. Never Forget What You Did and What You Have to Do Again</h4><p>Have you ever found yourself struggling to recall what you accomplished yesterday or right before heading off on a vacation during a standup meeting? Or perhaps you’ve forgotten to complete essential tasks like speccing a card or responding to questions? If so, there’s a remedy, which is establishing a robust to-do workflow.</p><p><strong><em>Personal anecdote</em></strong></p><p>My preferred tool for this purpose is <a href="https://www.notion.so/">Notion</a>. I create a Day Tasks board where I list everything I need to work on, what I’m currently tackling, and what I’ve already completed. I also use it to track ongoing conversations or threads that require my input.</p><p>Whenever someone assigns a task, whether it’s speccing a ticket or resolving a merge conflict, and I can’t address it immediately, I simply add it to my to-do list for later tracking. This approach keeps me consistently ahead of my tasks.</p><p>One additional feature I appreciate about using Notion for this purpose is that I can attach notes and comments to these daily tasks. This allows me to easily retrieve context or useful links from past tasks using the search bar, which has proven invaluable on numerous occasions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyMwPVB0klcXHVcusPMf1Q.png" /><figcaption>Example of Notion’s Board for tracking day tasks</figcaption></figure><p>I’ve made a <a href="https://www.notion.so/fe1716c02ac4406fa4159002c9a6da65?pvs=21">live version</a> of the above example, so you can view and duplicate it.</p><blockquote>💡 <strong>Leverage Slack’s “Remind Me Later” Feature</strong></blockquote><blockquote>Are you using Slack? One of its great features is “Remind Me Later.” Instead of relying solely on a Day Task board or manual tracking for threads to reply to or tasks you’ve been assigned to, you can simply ask Slack to remind you about them at a later time.</blockquote><blockquote>If you use other communication tools, check if they offer similar features and make sure to use it.</blockquote><h4>16. Leverage Your Calendar</h4><p>Your Google Calendar or similar tools are invaluable for efficient day organization. Ensure you use them effectively to schedule your daily tasks.</p><p>Consider blocking 15 minutes at the end of each working day to plan your agenda for the next day. This practice can greatly enhance your productivity by providing a structured plan for your tasks and priorities.</p><h4>17. Schedule Time for Small Tasks</h4><p>Dedicating an entire day to a single task may not always be the most productive approach. To boost your productivity, allocate recurring time slots in your calendar for tasks such as PR reviews, card refinement (speccing), etc. Also, schedule on-demand time slots to handle small, ad-hoc requests like reviewing an RFC or babysitting a PR. This strategy will enable you to accomplish more, unblock your colleagues, and sustain a clear mindset.</p><p>When it is time for these tasks, consider briefly pausing what you are working on to address them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCs8q2fIuDw2L49ERCJsnA.png" /><figcaption>Example of recurring tasks for PR Review and day planning</figcaption></figure><h4>18. Have Dedicated Focus Time</h4><p>Allocate specific periods for focus time, where you enter your “zen mode.” This is the time to eliminate distractions and concentrate on creating or accomplishing tasks without interruptions.</p><p>Remember to snooze your notifications and update your status, signaling to others that you’re in a focused state, making it less likely for them to interrupt you.</p><h4>19. Save Time by Asking Questions</h4><p>While exploring and learning new things is valuable, it’s not always the most time-efficient approach. When faced with a challenge or unfamiliar task, consider seeking shortcuts by asking your colleagues for guidance and brainstorming on how to accomplish it. This can save you significant time and prevent unnecessary frustration.</p><h4>20. Nudge People to Unblock You</h4><p>Delays caused by blockers can harm both your productivity and team efficiency. When waiting on others, gently nudge them to take action. Ensuring that tasks requiring their input are completed promptly benefits everyone involved and helps prevent a sudden pile-up of tasks, which can disrupt your workflow and make context-switching challenging.</p><h4>Bonus: Find your way</h4><p>As we conclude this article, it’s important to remember that the tips shared here reflect my personal perspective and what worked for me. While some of them may resonate with you, others may not. What truly matters is using these tips, along with others, as a stepping stone to find your own unique way.</p><p>I hope you found this article insightful!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b45766724f51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/studocu-techblog/20-practical-productivity-tips-that-you-can-start-doing-today-as-a-developer-no-pomodoro-b45766724f51">20 practical productivity tips that you can start doing today as a developer (no Pomodoro)</a> was originally published in <a href="https://medium.com/studocu-techblog">Studocu Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You might not need a repository in Laravel: 3 alternatives]]></title>
            <link>https://medium.com/studocu-techblog/you-might-not-need-a-repository-in-laravel-3-alternatives-c241638a3922?source=rss-7928fab44e3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c241638a3922</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Mazen Touati]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 09:10:34 GMT</pubDate>
            <atom:updated>2023-03-07T21:39:13.477Z</atom:updated>
            <content:encoded><![CDATA[<p>The repository pattern is a bit controversial on how it is being used in Laravel projects. Different developers have different needs and motivations. Some are adhering to the textbook definitions and others are using it to dump their queries.</p><p>In this article, we will revisit the state of the art of the repository pattern with its pros and cons. Then, we will walk through three alternatives to architect our codebase around queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o507g-xN7ps3F5stNxt1vA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@heysupersimi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Simone Hutsch</a> on <a href="https://unsplash.com/photos/xOLhD-qfoRI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>—</p><p>After reading this article, you will:</p><ul><li>Get familiar with the repository pattern, its pros, and its cons.</li><li>Be able to use Eloquent Scopes.</li><li>Be able to use Custom Queries.</li><li>Be able to use Actions.</li></ul><h3>So what’s a repository anyway?</h3><p>In a nutshell, the repository pattern is an abstraction layer between your data storage and your business logic. It is a good application of the <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle"><em>Dependency Inversion Principle (DIP)</em></a><em> </em>as we will be dealing with abstracted interfaces instead of concrete implementations (see diagram 1 below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibo4IwSVi6fN3Y4Pv-sEpg.png" /><figcaption>diagram 1: The repository pattern</figcaption></figure><p>The main benefits are:</p><ul><li>Separation of concerns.</li><li>Re-usability.</li><li>Caching accessed data.</li><li>Swappability.</li><li>Testability.</li></ul><h4>Implementation</h4><p>To use a repository pattern, you will need to have interfaces and a concrete implementation for each storage layer. The following is an example of such implementation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7nadAX52R4wA3ry0m8i8Hw.png" /><figcaption>diagram 2: Repository pattern Implementation example</figcaption></figure><p><em>Note: </em>in the above example, we have a separate repository for accessing data through cache (<em>BookCacheRepository</em>). That’s one option, the other option is that you cache the results directly within the main repository. More on this later.</p><p><strong>An example in Laravel,</strong></p><pre>// First we bind the interfaces to the implementation.<br>class AppServiceProvider extends ServiceProvider<br> // ...<br><br>   public function register(): void<br>   {<br>      $this-&gt;app-&gt;bind(BookRepositoryInterface::class, BookEloquentRepostiory::class);<br>      $this-&gt;app-&gt;bind(ProductRepositoryInterface::class, ProductThirdPartyRepostiory::class);<br>   }<br>}<br><br>// Then we can use it in our Business logic using dependency injection.<br>class FooController extends Controller<br>{<br><br>   public function __invoke(BookRepositoryInterface $repostiory)<br>   {<br>      // ...<br>      $data = $repostiory-&gt;get();<br>   }<br>}</pre><blockquote>In the above example the binding is hardcoded. Depending on the use case, the binding could be dynamic. Like binding to a specific repository based on whether the request is a web request or an api call.</blockquote><h4>Main benefits</h4><p>In this section, I’ll detail two points that make the pattern distinguished: Swappability and Testability. The remaining points speak for themselves.</p><h4><strong>Swappability</strong></h4><p>Thanks to <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">DIP</a>, the business logic is indifferent to the implementation. Thus, we can easily swap the implementation details without changing the business logic.</p><p>Let’s imagine you’re running a shop and one day you decided to externalize your inventory management. The third-party service provides an API to communicate with it. Let’s assume your business logic is bound to <em>ProductRepositoryInterface.</em> With that in mind, you will only need to create a new implementation that interacts with the API instead of the Database. Then you will bind the new implementation to the said interface in the <a href="https://laravel.com/docs/9.x/container">container</a>. Everything will still work as expected.</p><p><strong>It sounds great, is there a catch?</strong></p><p>While researching this article, I came across many examples of the repository pattern in Laravel. Most of them (if not all) are coupled with Eloquent and its Collections. Which makes it impossible to swap it with a completely different data storage or <a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping">ORM</a>.</p><p>Therefore, to make the swap possible you should not couple your interfaces to Eloquent jargon. When using a different data layer, most likely you’re not using Eloquent anymore.</p><p>You might argue that for the above API example, you can still hydrate the results into Eloquent models. That’s a risky workaround because Eloquent is an <a href="https://en.wikipedia.org/wiki/Active_record_pattern">Active Record Pattern</a> implementation. It represents a relational database record while being able to update and persist it.</p><p><strong><em>Takeaway/TL;DR</em></strong></p><p>Swapping the implementation is a lucrative concept. It sounds very beneficial, yet, to do it right you should not couple it with Eloquent. Except for, using the repository pattern only to separate the data and cache layers (see diagram 2 above) or to have mocks/fakes (see next section).</p><p>Are you confident that one day you will swap the implementation? If the answer is yes, then you can go for it. Otherwise, you can stick with <a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">YAGNI</a>, rarely, you will ever need to have something other than Eloquent in your Laravel project.</p><h4>Testability</h4><p>Thanks to the swappability, we can have different implementations for tests where we don’t interact with a real database (a.k.a test <a href="https://en.wikipedia.org/wiki/Mock_object#Mocks,_fakes,_and_stubs">mocks/fakes</a>).</p><p>The main arguments for faking the database implementation are:</p><ul><li>Fast tests</li><li>Less prone to random failure tests.</li></ul><p>Some might go for an in-memory database like SQLite. I wanted to mention this here, as the arguments and concepts are the same hence the downsides.</p><p>The catch is, it is risky and produces inconclusive tests. The tests won’t be running against the same database that runs your production server.</p><p>You’re not asserting the database works as expected in different scenarios. Your production might break after deploying an incompatible database change. Or, due to the differences in the default behavior for each <a href="https://en.wikipedia.org/wiki/Database#Database_management_system">DBMS</a>, you might have system in-correctness.</p><p><strong>How can you make your tests fast/resilient without faking?</strong></p><p>Laravel provides a <a href="https://laravel.com/docs/9.x/database-testing#resetting-the-database-after-each-test"><strong>RefreshDatabase</strong></a> trait, which makes testing with real databases more convenient. You will be dealing with a small dataset and a clean state each time.</p><p><strong><em>Takeaway/TL;DR</em></strong></p><p>It is safer, although slower, to run your tests against an actual mirror of your production database. Avoid swaps, mocks, and different databases during tests. Test against what your production is using.</p><h4>Why the Repository Pattern Can’t Keep Up?</h4><p>You might get away with the repository pattern in simple projects. However, the more business logic you add, the more complex these repositories get.</p><p>Let’s have an example,</p><p>We have a book repository with a method all to fetch all books. At some point, you added premium books and premium membership. Now, you want all to return all books for premium users but only the non-premium books for unpaid users.</p><p>How would you solve this? Here are some suggestions:</p><ul><li>Add an extra parameter (like the user object or a flag) to all to filter the books.</li><li>Add an extra method for unpaid users, like allWithoutPremium.</li><li>Add a separate repository for premium users.</li></ul><p>Later, we introduced two new features: anonymous books and roles. Only users with an administrator role should see the authors. We want to conditionally load this relation.</p><p>What changes will you introduce to your repository?</p><p>Did you see the problem here with a growing project? Repositories don’t usually scale well. They will easily collect <a href="https://en.wikipedia.org/wiki/Code_smell">code smells</a> as the logic becomes complicated. You will end up with massive repositories in terms of size and cognitive load.</p><p>In the next part, we will explore together three alternatives to overcome these issues and make our codebase more readable and maintainable.</p><h3>Repository pattern alternatives</h3><p>In this part, we will go through alternative ways to abstract the queries from the business logic. Thus, having readable, maintainable, and testable code. The alternatives are not a 1:1 replacement for the repository pattern. However, they are ways to encapsulate away data access and manipulation.</p><h4>Eloquent Scopes</h4><p>As it is being assumed that you’re going to stick with Eloquent as an ORM then let’s keep the code <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> with <a href="https://laravel.com/docs/9.x/eloquent#query-scopes">scopes</a>.</p><p>Scopes are the most primitive/low-level alternative we have on the list. Basically, a scope will allow you to factorize common constraints for your models.</p><p>Let’s follow up with the earlier example, we have books fetched and used all over the place. We want to conditionally load either free books only or all books including premium. It will be based on the logged-in user.</p><p>Using scopes for the book states in this case is a great idea. Here’s an example of how it might look like,</p><pre>&lt;?php<br> <br>namespace App\Models;<br> <br>use Illuminate\Database\Eloquent\Model;<br> <br>class Book extends Model<br>{<br>    public function scopeWhereFree(Builder $query): void<br>    {<br>      $query-&gt;where(&#39;is_premium&#39;, false);<br>    }<br><br><br>    public function scopeWherePublished(Builder $query): void<br>    {<br>      $query-&gt;whereNotNull(&#39;published_at&#39;);<br>    }<br>}</pre><p>you can use the above scope as the following in your code,</p><pre>&lt;?php<br><br>use App\Models\Book;<br><br>// ...<br><br>Book::query()<br> -&gt;wherePublished()<br> -&gt;when(!Auth::user()?-&gt;isPremium(), fn(Builder $query) =&gt; $query-&gt;whereFree())<br> -&gt;latest()<br> -&gt;limit(10)<br> -&gt;get();</pre><p>The above query will load all books by default, however, when the user is not logged in or not premium, we will limit the results to the free books only.</p><p>When using scopes, you create one place that holds the criteria. If tomorrow you want to change what would be considered a free or a published book you only need to change the scope.</p><p>Scopes set the foundation for the next options, as they serve as a great building block. They can also be used within repositories.</p><blockquote>Bonus Tip: you might also consider using Custom Query Builders in Laravel to further expand your model’s query builder and slim down your models.</blockquote><h4>Custom Queries</h4><p>A custom query is a way to define complex constraints for fetching data while providing a business context. You can think of it as a complex method in a repository, however, these would be standalone classes.</p><p>You can have a line between a custom query and a scope. The moment you start thinking about limiting data, ordering, caching, joins, or any other custom logic you have to use a custom query instead.</p><p><strong>Let’s have an example</strong></p><p>We want to fetch a set of premium books for a particular category. We should only fetch a pre-defined number of books and order them by date from most recent to least recent.</p><p>When the category is archived, we should only fetch books without users (it does not make a lot of sense, but it is just for the sake of the example).</p><p>With that in mind, we can have the following custom query,</p><pre>&lt;?php<br><br>namespace App\Queries\Books;<br><br>class LatestPremiumBooksOfCategoryQuery<br>{<br> public function __constructor(<br>    private readonly Category $category,<br>    private readonly ?int $limit = null,<br> ): void<br> {<br>    $this-&gt;limit ??= config(&#39;categories.limit&#39;);<br> }<br><br> /**<br> * @return Collection&lt;Book&gt;<br> */<br>  public function get(): Collection<br> {<br>   return $this<br>         -&gt;category<br>         -&gt;books()<br>         -&gt;wherePublished()<br>         -&gt;wherePremium()<br>         -&gt;when($this-&gt;category-&gt;isArchived(), fn(Builder $builder) =&gt; $builder-&gt;whereNull(&#39;books.user_id&#39;))<br>         -&gt;latest()<br>         -&gt;take($this-&gt;limit)<br>         -&gt;get();<br>    }<br><br><br>// usage<br><br>(new LatestPremiumBooksOfCategoryQuery($category))-&gt;get();</pre><p><em>Note:</em> In the above example, we only have one public method to get all results. You can add as many public access points as needed, for example, paginate() to get paginated data. You can factorize the common part into a separate private method like query()</p><p><strong>Caching strategy</strong></p><p>In the above query, we didn’t have any caching. However, it would be up to you how to cache the results.</p><p>We can cache the results in two ways: Cache the entire data or Cache the ids only*.</p><p>* The idea is to cache the ids, and the next time, you will fetch the data using where in, which will perform faster than the original filters (when finding the ids in the first place). Similar to Laravel’s SerializesModels for <a href="https://laravel.com/docs/9.x/queues#class-structure">jobs</a>.</p><p><em>Pros and cons</em></p><figure><img alt="Custom Query caching strategies pros and cons" src="https://cdn-images-1.medium.com/max/723/1*6LHD7vgwlodE_VkrqvRevw.png" /><figcaption>Custom Query caching strategies pros and cons</figcaption></figure><blockquote>The pros and cons of each strategy almost contrast each other. Thus, you might use a combination of both as well. It depends on what’s being cached and how it is being used.</blockquote><p><strong>Rules</strong></p><p>For consistency, you will need to have a set of rules on how to use them in your organization.</p><p>At <a href="https://studocu.com/">Studocu</a>, we are using the following set of rules,</p><p><strong>Do</strong></p><ul><li>Eager load relationships.</li><li>Define Select / Where / Joins / OrderBy / Limit on queries.</li><li>Deal with Cache.</li><li>Expose all use-case access-point methods like get or first methods (but never expose the builder).</li></ul><p><strong>Don’t</strong></p><ul><li>Deal with the presentation layer (returning JsonResource for example).</li><li>Execute queries other than SELECT.</li></ul><p><strong>Testing</strong></p><p>The custom query’s goal is to <strong>fetch</strong> the data you need <strong>accurately.</strong> Thus it is important to assert it is doing it properly.</p><p>You need to make sure the test is as conclusive as possible. For example, to test the above query, you need to ensure the following:</p><ul><li>Seeding books for the target category with and without eligibility criteria.</li><li>Seeding books for <strong>other</strong> categories with and without eligibility criteria.</li><li>Set predictable order for the books.</li></ul><p>This way, you will ensure the query is selective about the data it gets.</p><p>In general, these are some of the things you need to assert when testing your queries:</p><ul><li>Filtering by FKs.</li><li>Filtering by states.</li><li>Filtering by thresholds.</li><li>Ordering.</li><li>Limiting.</li></ul><p>The following is an example for testing the above custom query,</p><pre>&lt;?php<br><br>class LatestPremiumBooksOfCategoryQueryTest extends TestCase<br>{<br>    use RefreshDatabase;<br>    use WithFaker;<br><br>    private const LIMIT = 5;<br><br>    /** @test */<br>    public function it_works_for_non_archived_categories(): void<br>    {<br>        // Arrange<br><br>        $categories = Category::factory()-&gt;count(4)-&gt;create()-&gt;shuffle();<br><br>        $targetCategory = $categories-&gt;pop();<br><br>        $expectedBooks = $this-&gt;seedBooks($targetCategory);<br><br>        $categories<br>            -&gt;each(function (Category $category) {<br>                // Seed books that should not be included.<br>                $this-&gt;seedBooks($category);<br>            });<br><br>        // Act<br><br>        $result = (new LatestPremiumBooksOfCategoryQuery($targetCategory, self::LIMIT))-&gt;get();<br><br>        // Assert<br><br>        $this-&gt;assertCount(self::LIMIT, $result);<br><br>        $this-&gt;assertEquals(<br>            $expectedBooks-&gt;toArray(),<br>            $result-&gt;toArray(),<br>        );<br>    }<br>}</pre><p>You can inspect the full test <a href="https://github.com/sunchayn/you-might-not-need-a-repository-in-laravel/blob/master/tests/Functional/Modules/Books/Queries/LatestPremiumBooksOfCategoryQueryTest.php">here</a>.</p><blockquote>Bonus Tip: you can further encapsulate your queries using ViewModels. Spatie has a <a href="https://github.com/spatie/laravel-view-models">ViewModels package</a> that will make the implementation seamless.</blockquote><p><strong>Takeaways</strong></p><p>The custom query classes will help hide all the builder chaining while providing the possibility to adapt to many use cases like caching the results (with optional serialization), re-using results from other queries (including custom queries), early exits, dynamic empty states, custom eager loading, accepting query parameters and acting upon them, etc.</p><blockquote>You can check a non-working complex example of a Custom Query Class <a href="https://github.com/sunchayn/you-might-not-need-a-repository-in-laravel/blob/master/app/Modules/Example/Queries/ComplexCustomQueryExample.php">here</a> where it showcases what you can do inside a custom query class.</blockquote><h4>Actions</h4><p>An action is a class that performs a domain-specific task. It ranges from simple operations like creating, updating, or deleting data to performing complex logic like merging two models and migrating all related data from one to another.</p><p>You can think of them as the <strong>CUD</strong> part of a repository (which is CRUD) plus the business logic of a service.</p><p>Actions are highly reusable across different applications and composable within each other.</p><p><strong>Implementation</strong></p><p>There’s no standardized practice for Actions in Laravel. You can come across different implementations. Yet, they are all orbiting around the same concept. It is a good idea to regulate the implementation details in your organization.</p><p>At <a href="https://studocu.com/">Studocu</a>, we use the following rules:</p><ol><li>Actions must not be extended nor extend. We will rely on composition instead. <em>Note: You can enforce using the final keyword instead, however, it won’t allow you to mock the actions during testing. Unless you are doing </em><a href="https://en.wikipedia.org/wiki/Black-box_testing"><em>black-box testing</em></a><em> which implies you’re not testing the actions in isolation.</em></li><li>Action classes must use <strong>dependency injection</strong> in the constructor to resolve the dependencies. Hence, they should be injected as well.</li><li>Action classes must have <strong>only one public method</strong>, called execute. The parameters and return of that method changes per class. All other methods and properties should be declared private.</li><li>The execute method can take a max of 1 parameter. If you need more, use a <a href="https://en.wikipedia.org/wiki/Data_transfer_object">DTO</a>. <em>Note: DTOs will help make the action reusable. They will be constructed using factories based on the context in which they are being used.</em></li></ol><p><strong>Actions in Action</strong></p><p>Let’s create an action to publish our books. We want to be able to do the following:</p><ul><li>Save who did the operation.</li><li>Make the book premium when requested.</li><li>Dispatch a “book published” event. So event listeners can run. For example, to send emails to users that we have a new book available.</li></ul><p>With that in mind, we can create the following action,</p><pre>&lt;?php<br><br>class PublishBookAction<br>{<br>    public function execute(PublishBookData $data): void<br>    {<br>        $data-&gt;book-&gt;markAsPublishedBy($data-&gt;user);<br><br>        if ($data-&gt;shouldBePremium) {<br>            $data-&gt;book-&gt;markAsPremium();<br>        }<br><br>        $data-&gt;book-&gt;save();<br><br>        event(new BookPublishedEvent($data-&gt;book));<br>    }<br>}</pre><pre>&lt;?php<br><br>final class PublishBookData<br>{<br>    public function __construct(<br>        public readonly Book $book,<br>        public readonly User $user,<br>        public readonly bool $shouldBePremium,<br>    ) {<br>    }<br><br>    public static function fromBookPublishRequest(PublishBookStoreRequest $request): self<br>    {<br>        $data = $request-&gt;validated();<br><br>        $book = Book::findOrFail($request-&gt;route(&#39;book_id&#39;));<br><br>        return new self(<br>            book: $book,<br>            user: $request-&gt;user(),<br>            shouldBePremium: $data[&#39;should_be_premium&#39;] ?? false,<br>        );<br>    }<br>}</pre><p><strong>Takeaways</strong></p><p>In the above example, we used an action to publish a book, while adhering to the business rules. We’ve transported the data using Action-specific DTOs.</p><p>The latter handles querying and initializing all the required input data for the action. We used static factories to make instantiating them from different contexts easy.</p><blockquote>You can read more about actions, different use cases and how they can be composed in this <a href="https://stitcher.io/blog/laravel-beyond-crud-03-actions">article</a> by <a href="https://twitter.com/brendt_gd">Brent</a>.</blockquote><p><strong>Testing</strong></p><p>You might test actions in isolation or as part of a <a href="https://en.wikipedia.org/wiki/Black-box_testing">black-box</a> feature test, or both of them together. It is up to you and your organization how you approach tests.</p><p>Black-box testing is helpful if you’re using <a href="https://en.wikipedia.org/wiki/Test-driven_development">TDD</a> and it will make refactoring a lot easier. Your tests will serve as a documentation and assertion gate for your features.</p><p>The following is an example of how to black-box test the book publishing endpoint,</p><pre>class PublishBookTest extends TestCase<br>{<br>    use RefreshDatabase;<br><br>    /**<br>     * @dataProvider publishBookDataProvider<br>     * @test<br>     */<br>    public function it_publishes_books(array $requestParams, bool $expectedToBePremium): void<br>    {<br>        // Arrange<br><br>        Event::fake();<br><br>        $book = Book::factory()-&gt;free()-&gt;unpublished()-&gt;create();<br><br>        $user = User::factory()-&gt;create();<br><br>        Carbon::setTestNow(today());<br><br>        // Act<br><br>        $response = $this<br>            -&gt;actingAs($user)<br>            -&gt;postJson(route(&#39;books.publish&#39;, [&#39;book_id&#39; =&gt; $book-&gt;id, ...$requestParams]));<br><br>        // Assert<br><br>        $response-&gt;assertOk();<br><br>        $book-&gt;refresh();<br><br>        $this-&gt;assertEquals($expectedToBePremium, $book-&gt;isPremium());<br><br>        $this-&gt;assertEquals($user-&gt;id, $book-&gt;published_by);<br><br>        $this-&gt;assertEquals(today(), $book-&gt;published_at);<br><br>        Event::assertDispatched(<br>            BookPublishedEvent::class,<br>            fn (BookPublishedEvent $event) =&gt; $event-&gt;book-&gt;is($book),<br>        );<br>    }<br><br>    public function publishBookDataProvider(): array<br>    {<br>        return [<br>            &#39;it publish book as free book [explicit]&#39; =&gt; [<br>                &#39;params&#39; =&gt; [<br>                    &#39;should_be_premium&#39; =&gt; false,<br>                ],<br>                &#39;expectedToBePremium&#39; =&gt; false,<br>            ],<br>            &#39;it publish book as free book [implicit]&#39; =&gt; [<br>                &#39;params&#39; =&gt; [],<br>                &#39;expectedToBePremium&#39; =&gt; false,<br>            ],<br>            &#39;it publish book as premium book&#39; =&gt; [<br>                &#39;params&#39; =&gt; [<br>                    &#39;should_be_premium&#39; =&gt; true,<br>                ],<br>                &#39;expectedToBePremium&#39; =&gt; true,<br>            ],<br>        ];<br>    }<br>}</pre><p>In the above example, only one test has been included to not over-charge the article. You can inspect the full test <a href="https://github.com/sunchayn/you-might-not-need-a-repository-in-laravel/blob/master/tests/Api/Books/PublishBookTest.php">here</a>.</p><h3>Closing notes</h3><p>We revisited the repository pattern with its pros and cons. Mainly the swappability which allows externalizing parts of your app, separating data and cache layers, or making tests run faster.</p><p>Then, we saw three alternatives that together can abstract your data management:</p><ul><li>Laravel scopes to supercharge Eloquent with business-related queries.</li><li>Custom Queries to fetch and cache your complex data.</li><li>Actions to manipulate your data.</li></ul><p>In the end, I want to highlight that these alternatives are not what you should use, rather, they are what you <strong>can</strong> use. I hope this was insightful, let me know what you think in the comments.</p><p>You could check this GitHub <a href="https://github.com/sunchayn/you-might-not-need-a-repository-in-laravel/">repository</a> for all the examples mentioned above.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c241638a3922" width="1" height="1" alt=""><hr><p><a href="https://medium.com/studocu-techblog/you-might-not-need-a-repository-in-laravel-3-alternatives-c241638a3922">You might not need a repository in Laravel: 3 alternatives</a> was originally published in <a href="https://medium.com/studocu-techblog">Studocu Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>