<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ivan Firestone</title>
    <description>The latest articles on DEV Community by Ivan Firestone (@ifirestone).</description>
    <link>https://dev.to/ifirestone</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F586402%2F81648520-139b-4cc1-96b0-96ed14e30d08.jpeg</url>
      <title>DEV Community: Ivan Firestone</title>
      <link>https://dev.to/ifirestone</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ifirestone"/>
    <language>en</language>
    <item>
      <title>Data Objects, Concerns and Events: The Supporting Cast of a Laravel Action: 04 of 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Sat, 14 Nov 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/ifirestone/data-objects-concerns-and-events-the-supporting-cast-of-a-laravel-action-04-of-08-115i</link>
      <guid>https://dev.to/ifirestone/data-objects-concerns-and-events-the-supporting-cast-of-a-laravel-action-04-of-08-115i</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1640158615573-cd28feb1bf4e%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDJ8fGRhdGElMjBvYmplY3RzfGVufDB8fHx8MTc5Mjc5MjQyMXww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1640158615573-cd28feb1bf4e%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDJ8fGRhdGElMjBvYmplY3RzfGVufDB8fHx8MTc5Mjc5MjQyMXww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Data Objects, Concerns and Events: The Supporting Cast of a Laravel Action: 04 of 08" width="2000" height="1333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Imagine that the approval Action from the previous article stays clean for about a month. Then the product asks for four small things: email the customer, push the invoice to the ledger, write an audit entry, and ping the sales channel. Each one fits into the transaction in three lines. After four requests the Action is the new fat controller, and its signature has quietly become &lt;code&gt;handle(array $data)&lt;/code&gt;, where nobody remembers which keys are required.&lt;/p&gt;

&lt;p&gt;An Action solves where the rule lives. It doesn't solve what feeds it, what it shares with other classes, or what it should announce to the rest of the app. Three smaller tools cover those: Data objects for input, Concerns for shared capabilities and Events for side effects. Each is easy to misuse, so this article spends as much time on where each one stops as on how it works.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Array That Knew Too Much
&lt;/h2&gt;

&lt;p&gt;An array of input has no shape. Is the key &lt;code&gt;due_date&lt;/code&gt; or &lt;code&gt;dueDate&lt;/code&gt;? Is &lt;code&gt;notes&lt;/code&gt; optional? Is the quantity a string because it came from a form post? The Action can't tell you, your editor can't either, and a typo fails at runtime in production.&lt;/p&gt;

&lt;p&gt;A Data object gives the input a name and a type. In modern PHP that is a readonly class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;IssueInvoiceData&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/** @param list&amp;lt;InvoiceLineData&amp;gt; $lines */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$customerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;CarbonImmutable&lt;/span&gt; &lt;span class="nv"&gt;$dueDate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$lines&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$notes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;fromRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StoreInvoiceRequest&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$input&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;validated&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'customer_id'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;dueDate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CarbonImmutable&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'due_date'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;lines&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;array_map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceLineData&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;fromArray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'lines'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;notes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'notes'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;(int)&lt;/code&gt; cast is there on purpose. Form posts deliver strings, and the Data object is the one place that converts them. &lt;code&gt;InvoiceLineData&lt;/code&gt; is another readonly class built the same way. Readonly classes need PHP 8.2 or later.&lt;/p&gt;

&lt;p&gt;Now the Action asks for what it needs, and every caller has to supply it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;IssueInvoiceData&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="nv"&gt;$author&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same object works from a controller, a console import, a queued job payload or a test, with no copy of the mapping logic.&lt;/p&gt;

&lt;p&gt;There are limits. A Data object holds data and the shape of data. It doesn't query the database, apply business rules or carry Eloquent models around. And it is overkill for a method with two scalar arguments: &lt;code&gt;ApproveInvoice&lt;/code&gt; doesn't need one. Packages such as &lt;a href="https://spatie.be/docs/laravel-data/v4/introduction?ref=blog.ifirestone.dev" rel="noopener noreferrer"&gt;&lt;code&gt;spatie/laravel-data&lt;/code&gt;&lt;/a&gt; automate the mapping, and they are worth a look once writing &lt;code&gt;fromRequest&lt;/code&gt; by hand starts to hurt. Plain readonly classes are enough until then.&lt;/p&gt;

&lt;h2&gt;
  
  
  What a Concern Is For
&lt;/h2&gt;

&lt;p&gt;Laravel itself puts shared model behavior in a &lt;code&gt;Concerns&lt;/code&gt; namespace, and the habit is worth copying. A Concern is a trait that gives many classes the same small capability. The tenant article had a good one, &lt;code&gt;BelongsToCompany&lt;/code&gt;: it attaches a scope, fills a column, and applies to every tenant-owned model. Another might be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;trait&lt;/span&gt; &lt;span class="nc"&gt;Archivable&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;scopeActive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Builder&lt;/span&gt; &lt;span class="nv"&gt;$query&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$query&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;whereNull&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'archived_at'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;archive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;forceFill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'archived_at'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A quick test tells you whether something is a Concern. Can you name it as a capability, with a prefix like &lt;code&gt;Has&lt;/code&gt;, &lt;code&gt;Belongs&lt;/code&gt; or an adjective such as &lt;code&gt;Archivable&lt;/code&gt;? If the best name you can find is &lt;code&gt;HandlesInvoiceApproval&lt;/code&gt;, it is an Action wearing a trait.&lt;/p&gt;

&lt;p&gt;The failure mode is the junk drawer. A 3,000-line model split into eight traits is still a 3,000-line model, only harder to read, because the methods are in eight files and each trait quietly assumes columns that live somewhere else. Three costs to watch:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Hidden coupling: the trait uses &lt;code&gt;$this-&amp;gt;status&lt;/code&gt; without declaring it needs one.&lt;/li&gt;
&lt;li&gt;Name collisions between methods of different traits.&lt;/li&gt;
&lt;li&gt;Tests that only work through a model that uses the trait.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Keep Concerns small, capability-shaped and boring.&lt;/p&gt;

&lt;h2&gt;
  
  
  Events for the Things the Action Shouldn't Know About
&lt;/h2&gt;

&lt;p&gt;Back to the four requests. Sending the email, updating the ledger and pinging the channel are reactions to a fact: an invoice was approved. The Action doesn't need to know who reacts. It announces the fact, and whoever cares listens.&lt;/p&gt;

&lt;p&gt;A useful split: what must succeed or fail together with the approval stays inside the Action's transaction. What can happen later, or fail on its own, becomes a listener. The email is a listener. The status change is not.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceApproved&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;ShouldDispatchAfterCommit&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Dispatchable&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$invoiceId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$companyId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;ShouldDispatchAfterCommit&lt;/code&gt; interface matters. Per the &lt;a href="https://laravel.com/docs/13.x/events?ref=blog.ifirestone.dev" rel="noopener noreferrer"&gt;Laravel events docs&lt;/a&gt;, such an event isn't dispatched until the open database transaction commits, and it is discarded if the transaction fails. Without it, a queued listener could run before the commit, or send an email for an approval that was rolled back.&lt;/p&gt;

&lt;p&gt;The Action dispatches it from inside the transaction, with ids rather than models, so the payload is small and explicit:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nc"&gt;InvoiceApproved&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;company_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The listener is where the tenant article comes back. A queued listener runs in a worker, with no URL and no user, so under a fail-closed scope it has no company. The fix is the job middleware we already know, which listeners support too. This version takes the id in its constructor, because a listener can't read it off the job the way the earlier example did:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;RunsAsCompany&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$companyId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;object&lt;/span&gt; &lt;span class="nv"&gt;$job&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Closure&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runAs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;companyId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$job&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SendApprovalEmail&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;ShouldQueue&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;middleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceApproved&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;RunsAsCompany&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;companyId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceApproved&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$invoice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;findOrFail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;invoiceId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="nc"&gt;Mail&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;to&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;InvoiceApprovedMail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The docs show the &lt;code&gt;middleware&lt;/code&gt; method on a listener receiving the event as its argument, which is what makes this work. Laravel discovers listeners by scanning the &lt;code&gt;Listeners&lt;/code&gt; directory for &lt;code&gt;handle&lt;/code&gt; methods with a type-hinted event, so there is no registration step. When you want to see the wiring, &lt;code&gt;php artisan event:list&lt;/code&gt; prints it.&lt;/p&gt;

&lt;p&gt;The whole path now looks like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxna0mk246xxbizq9jadj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fxna0mk246xxbizq9jadj.png" alt="Data Objects, Concerns and Events: The Supporting Cast of a Laravel Action: 04 of 08" width="800" height="164"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What This Costs You
&lt;/h2&gt;

&lt;p&gt;Events trade clarity for decoupling, and the bill arrives in four places:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Hidden flow.&lt;/strong&gt; Someone reading &lt;code&gt;ApproveInvoice&lt;/code&gt; can't see the email. Name events in the past tense, keep listeners few, and use &lt;code&gt;event:list&lt;/code&gt;. An event with one listener and no prospect of a second is a method call in disguise.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Eventual consistency.&lt;/strong&gt; The email arrives after the response, and the ledger may lag. The UI has to tolerate that.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Listeners can run twice.&lt;/strong&gt; Queues retry. Make each listener idempotent, so that a second email or a second ledger row isn't possible.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Testing in two parts.&lt;/strong&gt; Fake the event in the Action's test (&lt;code&gt;Event::fake([InvoiceApproved::class])&lt;/code&gt;) and test each listener on its own.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Data objects cost a class per use case. Concerns cost readability the moment they multiply. None of the three is free, and none is needed on day one.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The Action that was drifting toward &lt;code&gt;handle(array $data)&lt;/code&gt; now takes a typed object, leaves its capabilities to small Concerns, and announces what happened instead of doing everyone's chores. What changed isn't the amount of code. It's that each piece has a reason to exist and a reason to stop.&lt;/p&gt;

&lt;p&gt;For today: find one Action with an array argument and give it a Data object, and find one trait whose name is a verb phrase and ask whether it is really an Action. The last article in the series steps back from the code and looks at the order in which a project like this actually gets built and shipped.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>architecture</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>De la idea al primer cliente de pago: una hoja de ruta de entrega para un SaaS multi-tenant en Laravel: 05 de 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Thu, 12 Nov 2026 13:00:00 +0000</pubDate>
      <link>https://dev.to/ifirestone/de-la-idea-al-primer-cliente-de-pago-una-hoja-de-ruta-de-entrega-para-un-saas-multi-tenant-en-24cc</link>
      <guid>https://dev.to/ifirestone/de-la-idea-al-primer-cliente-de-pago-una-hoja-de-ruta-de-entrega-para-un-saas-multi-tenant-en-24cc</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Un plan trabajando hacia atrás para llevar un SaaS multi-tenant en Laravel de la idea al primer cliente de pago: criterios de éxito, orden de construcción, límites de plan, webhooks de facturación idempotentes, logs por tenant y despliegues seguros.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1534972195531-d756b9bfa9f2%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDV8fGRldmVsb3B8ZW58MHx8fHwxNzkyNzg4MjAzfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1534972195531-d756b9bfa9f2%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDV8fGRldmVsb3B8ZW58MHx8fHwxNzkyNzg4MjAzfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="De la idea al primer cliente de pago: una hoja de ruta de entrega para un SaaS multi-tenant en Laravel: 05 de 08"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Imagina un equipo que empieza un SaaS multi-tenant como lo hacen la mayoría. La primera semana es login y registro. De la segunda a la sexta, pantallas de configuración, un panel de administración y un sistema de diseño. Nadie ha usado aún el producto para el único trabajo para el que existe, y el modelo de datos no sabe que las empresas deben estar separadas entre sí.&lt;/p&gt;

&lt;p&gt;El código de los artículos anteriores (aislamiento de tenants, Actions, Data objects, Events) es solo la mitad del proyecto. La otra mitad es el orden en que lo construyes y la evidencia que reúnes antes de cobrarle a alguien. Este artículo es ese plan, escrito hacia atrás desde el día en que un desconocido paga.&lt;/p&gt;

&lt;h2&gt;
  
  
  Empieza por el día en que un desconocido paga
&lt;/h2&gt;

&lt;p&gt;Antes de un plan, un resultado. Para una primera versión lo escribiría como un solo párrafo: una persona se registra, crea una empresa, invita a un colega, hace el trabajo central, llega al límite del plan gratuito y paga. Toda tarea que no sirva a esa frase espera.&lt;/p&gt;

&lt;p&gt;Luego conviértelo en criterios de éxito que puedas comprobar. Un primer conjunto podría ser:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Una empresa nueva puede completar el trabajo central sin tu ayuda.&lt;/li&gt;
&lt;li&gt;Ningún test, script o comprobación manual puede mostrarle a una empresa los datos de otra.&lt;/li&gt;
&lt;li&gt;Un límite de plan se aplica en un solo lugar y la app lo explica cuando se alcanza.&lt;/li&gt;
&lt;li&gt;Un pago, una cancelación y un cobro fallido cambian cada uno lo que la empresa puede hacer.&lt;/li&gt;
&lt;li&gt;Puedes responder "¿qué le pasó a la empresa X ayer?" desde tus logs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Escribe al lado las restricciones y los supuestos: tamaño del equipo, presupuesto, el único proveedor de pagos que usarás, los roles que crees necesitar. Los supuestos son la parte útil. Cada uno es algo que descubrirás que está mal, y es más barato descubrirlo mientras todavía es una línea en un documento.&lt;/p&gt;

&lt;h2&gt;
  
  
  Levanta los muros antes que las habitaciones
&lt;/h2&gt;

&lt;p&gt;El orden importa, y el tenancy va primero. Agregar una columna de empresa a treinta tablas después del lanzamiento es una de las migraciones más caras que puede enfrentar un SaaS, y una tabla olvidada es una fuga de datos. Un orden de construcción viable:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Empresas, membresía y roles, con el contexto de tenant y el scope que falla cerrado, y los tests de fuga que los acompañan.&lt;/li&gt;
&lt;li&gt;Un slice de punta a punta del trabajo central, construido con las convenciones de Action, Data object y controlador que vas a conservar.&lt;/li&gt;
&lt;li&gt;Las piezas en segundo plano que ese slice necesita (events, listeners y jobs), cada una corriendo dentro de un contexto de tenant.&lt;/li&gt;
&lt;li&gt;Planes y límites.&lt;/li&gt;
&lt;li&gt;Facturación.&lt;/li&gt;
&lt;li&gt;Todo lo demás, ordenado según lo que pidan los primeros clientes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;El razonamiento es simple. Los muros son difíciles de añadir después y las habitaciones son fáciles de agregar. La facturación necesita planes, y los planes necesitan algo que valga la pena limitar.&lt;/p&gt;

&lt;h2&gt;
  
  
  Un slice, hasta el fondo
&lt;/h2&gt;

&lt;p&gt;El segundo paso merece su propia sección, porque es el que más reduce el riesgo. Un slice vertical va de la migración a una pantalla y un test: la tabla con su &lt;code&gt;company_id&lt;/code&gt;, el modelo con su trait, el Data object, la Action, el controlador delgado, una vista, un test que intenta filtrar. Y despliégalo antes de empezar la segunda funcionalidad.&lt;/p&gt;

&lt;p&gt;Esa última parte parece prematura, y no lo es. Un slice en un entorno real saca a la luz los problemas que no viven en el código: el worker de colas que no está corriendo, el scheduler que no está programado, el mailer sin credenciales, el disco de almacenamiento con los permisos equivocados. Quieres encontrarte con ellos con una funcionalidad en juego, no con doce.&lt;/p&gt;

&lt;p&gt;El costo es que el primer slice es lento. Estás construyendo las convenciones y el pipeline a la vez. Los slices siguientes son rápidos porque el primero pagó el patrón.&lt;/p&gt;

&lt;h2&gt;
  
  
  Planes, límites y facturación
&lt;/h2&gt;

&lt;p&gt;Los límites tienden a filtrarse en el código como comprobaciones dispersas de &lt;code&gt;if ($company-&amp;gt;plan === 'free')&lt;/code&gt;. Pónlos detrás de una sola clase a la que llamen las Actions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;PlanLimits&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;assertCanAddMember&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Company&lt;/span&gt; &lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$limit&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;plan&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;maxMembers&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;members&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="nv"&gt;$limit&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;PlanLimitReached&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;for&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'members'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$limit&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;La clase asume que &lt;code&gt;plan&lt;/code&gt; es un cast a enum con un método &lt;code&gt;maxMembers()&lt;/code&gt;. Lo importante es la puerta única. Cuando cambian los precios, cambia un archivo, y la excepción da a todos los llamadores una forma coherente de explicar el límite.&lt;/p&gt;

&lt;p&gt;La facturación es donde los errores cuestan dinero. Algunas reglas ayudan, elijas el proveedor que elijas:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Trata al proveedor como fuente de verdad del estado de la suscripción, y guarda una copia local que lea la app. Nunca llames al proveedor en cada petición para decidir qué puede hacer una empresa.&lt;/li&gt;
&lt;li&gt;Verifica la firma de cada webhook antes de leer el cuerpo. Cómo depende del proveedor.&lt;/li&gt;
&lt;li&gt;Guarda cada evento con el id de evento del proveedor antes de hacer cualquier otra cosa, y responde rápido. Haz el trabajo real en una cola.&lt;/li&gt;
&lt;li&gt;Asume que los eventos llegan dos veces y fuera de orden.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__invoke&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Request&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Response&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;abort_unless&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;signature&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isValid&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;401&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$payload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;all&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$event&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;BillingEvent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;firstOrCreate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'provider_event_id'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$payload&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'id'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'type'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$payload&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'type'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'payload'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'received_at'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;wasRecentlyCreated&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;ProcessBillingEvent&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;noContent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;signature&lt;/code&gt; es un verificador específico del proveedor que escribes una sola vez. Respalda la columna &lt;code&gt;provider_event_id&lt;/code&gt; con un índice único, porque &lt;code&gt;firstOrCreate&lt;/code&gt; por sí solo no es atómico. Si dos entregas compiten, una falla en el índice y el reintento del proveedor encuentra la fila ya guardada. Para los eventos fuera de orden, haz que el job de procesamiento compare la marca de tiempo del evento con la última aplicada a esa suscripción y descarte lo que sea más antiguo.&lt;/p&gt;

&lt;h2&gt;
  
  
  Probar las partes que cuestan dinero
&lt;/h2&gt;

&lt;p&gt;No puedes probarlo todo, así que apunta a lo que sale caro cuando se rompe:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Aislamiento.&lt;/strong&gt; Los tests de fuga del primer artículo, más una guarda que verifique que toda tabla con &lt;code&gt;company_id&lt;/code&gt; use el trait.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Límites.&lt;/strong&gt; Por debajo del límite, justo en él y por encima.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Webhooks.&lt;/strong&gt; El mismo evento entregado dos veces produce un solo efecto, y un evento antiguo no sobrescribe un estado más nuevo.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;El camino feliz.&lt;/strong&gt; Un smoke test a nivel de navegador desde el registro hasta el trabajo central.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lo demás puede vivir casi todo como tests de Action, que son rápidos, con una capa fina de tests HTTP para autorización y validación. Esa es la forma que los artículos anteriores establecieron a propósito.&lt;/p&gt;

&lt;h2&gt;
  
  
  Desplegar sin despertar a nadie
&lt;/h2&gt;

&lt;p&gt;Durante un deploy, el código viejo y el nuevo corren un momento lado a lado. Las migraciones tienen que sobrevivir a eso. La disciplina habitual es expandir primero (añadir una columna nullable, desplegar código que escribe en ambas), luego rellenar, luego cambiar las lecturas y, en un release posterior, endurecer la restricción. Los backfills sobre datos de tenants se hacen mejor como un job por empresa en bloques, por las mismas razones que el job nocturno del primer artículo.&lt;/p&gt;

&lt;p&gt;Dos hábitos evitan la mayoría de las sorpresas. Reinicia los workers de colas en cada deploy, porque mantienen la aplicación arrancada en memoria y no notan el código nuevo por su cuenta (&lt;code&gt;php artisan queue:restart&lt;/code&gt; lo hace). Y mantén disponible el release anterior, para que el rollback sea un interruptor y no una reconstrucción. Eso solo funciona si las migraciones son retrocompatibles, y por eso el paso de expandir va primero.&lt;/p&gt;

&lt;h2&gt;
  
  
  Ver por tenant
&lt;/h2&gt;

&lt;p&gt;El último criterio de la lista era responder "¿qué le pasó a la empresa X ayer?". &lt;a href="https://laravel.com/docs/13.x/context?ref=blog.ifirestone.dev" rel="noopener noreferrer"&gt;Context&lt;/a&gt; de Laravel lo vuelve una sola línea. Añádela donde se resuelve el tenant:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nc"&gt;Context&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'company_id'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Según la documentación, el contexto se agrega a las entradas de log escritas durante la petición y también se captura cuando se despacha un job y se restaura mientras el job corre. Cada línea de log, desde la web y desde la cola, lleva ahora la empresa. Esto no reemplaza el contexto de tenant explícito para las consultas. Solo hace que los logs se puedan buscar. Envía el mismo id a tu rastreador de errores, y una pregunta de soporte se vuelve un filtro en lugar de una investigación.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusión
&lt;/h2&gt;

&lt;p&gt;El equipo del principio pasó seis semanas en habitaciones sin muros y sin cliente. El plan de aquí lo invierte: define el día en que alguien paga, levanta los muros, entrega un slice de punta a punta y luego añade límites y facturación en el orden del que depende el dinero.&lt;/p&gt;

&lt;p&gt;Lo que se deja fuera es tan parte del plan como lo que entra. El single sign-on, los precios por uso y las bases de datos por empresa tienen cada uno un punto en que vale la pena construirlos. Ese punto es un cliente que lo pide, no una corazonada. Hasta entonces, puedes escribir el primer párrafo de este artículo para tu propio producto y comprobar cuáles de sus frases ya puedes demostrar.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>softwareengineering</category>
      <category>testing</category>
    </item>
    <item>
      <title>Data objects, Concerns y Events: el reparto de apoyo de una Action en Laravel: 04 de 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Tue, 10 Nov 2026 13:00:00 +0000</pubDate>
      <link>https://dev.to/ifirestone/data-objects-concerns-y-events-el-reparto-de-apoyo-de-una-action-en-laravel-04-de-08-4o00</link>
      <guid>https://dev.to/ifirestone/data-objects-concerns-y-events-el-reparto-de-apoyo-de-una-action-en-laravel-04-de-08-4o00</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Qué corresponde a un Data object, un Concern o un Event alrededor de una Action de Laravel: reglas prácticas, las trampas (traits cajón de sastre, flujo oculto, eventos que corren sin tenant) y un ejemplo de facturas con tenant.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1711128676735-83d5d9d17e9a%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDIyfHxzYWFzfGVufDB8fHx8MTc5Mjc4NjYzMHww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1711128676735-83d5d9d17e9a%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDIyfHxzYWFzfGVufDB8fHx8MTc5Mjc4NjYzMHww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Data objects, Concerns y Events: el reparto de apoyo de una Action en Laravel: 04 de 08" width="2000" height="1500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Imagina que la Action de aprobación del artículo anterior se mantiene limpia durante un mes. Luego producto pide cuatro cosas pequeñas: enviar un correo al cliente, empujar la factura al libro mayor, escribir una entrada de auditoría y avisar al canal de ventas. Cada una cabe en la transacción en tres líneas. Tras cuatro peticiones, la Action es el nuevo controlador gordo, y su firma se ha vuelto sin hacer ruido &lt;code&gt;handle(array $data)&lt;/code&gt;, donde nadie recuerda qué claves son obligatorias.&lt;/p&gt;

&lt;p&gt;Una Action resuelve dónde vive la regla. No resuelve qué la alimenta, qué comparte con otras clases ni qué debe anunciar al resto de la app. Tres herramientas más pequeñas cubren eso: los Data objects para la entrada, los Concerns para las capacidades compartidas y los Events para los efectos secundarios. Las tres son fáciles de usar mal, así que este artículo dedica tanto tiempo a dónde se detiene cada una como a cómo funciona.&lt;/p&gt;

&lt;h2&gt;
  
  
  El array que sabía demasiado
&lt;/h2&gt;

&lt;p&gt;Un array de entrada no tiene forma. ¿La clave es &lt;code&gt;due_date&lt;/code&gt; o &lt;code&gt;dueDate&lt;/code&gt;? ¿&lt;code&gt;notes&lt;/code&gt; es opcional? ¿La cantidad es un string porque vino de un post de formulario? La Action no puede decirlo, tu editor tampoco, y un typo falla en tiempo de ejecución en producción.&lt;/p&gt;

&lt;p&gt;Un Data object le da a la entrada un nombre y un tipo. En PHP moderno eso es una clase readonly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;IssueInvoiceData&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/** @param list&amp;lt;InvoiceLineData&amp;gt; $lines */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$customerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;CarbonImmutable&lt;/span&gt; &lt;span class="nv"&gt;$dueDate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt; &lt;span class="nv"&gt;$lines&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="nv"&gt;$notes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;fromRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;StoreInvoiceRequest&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$input&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;validated&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;customerId&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'customer_id'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;dueDate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CarbonImmutable&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'due_date'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;lines&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;array_map&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceLineData&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;fromArray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'lines'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;notes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nv"&gt;$input&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'notes'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;??&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;El cast &lt;code&gt;(int)&lt;/code&gt; está ahí a propósito. Los posts de formulario entregan strings, y el Data object es el único lugar que los convierte. &lt;code&gt;InvoiceLineData&lt;/code&gt; es otra clase readonly construida igual. Las clases readonly necesitan PHP 8.2 o superior.&lt;/p&gt;

&lt;p&gt;Ahora la Action pide lo que necesita, y cada llamador tiene que proporcionarlo:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;IssueInvoiceData&lt;/span&gt; &lt;span class="nv"&gt;$data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="nv"&gt;$author&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;El mismo objeto sirve desde un controlador, una importación por consola, el payload de un job en cola o un test, sin copiar la lógica de mapeo.&lt;/p&gt;

&lt;p&gt;Hay límites. Un Data object contiene datos y la forma de los datos. No consulta la base de datos, no aplica reglas de negocio ni pasea modelos de Eloquent. Y es excesivo para un método con dos argumentos escalares: &lt;code&gt;ApproveInvoice&lt;/code&gt; no necesita uno. Paquetes como &lt;a href="https://spatie.be/docs/laravel-data/v4/introduction?ref=blog.ifirestone.dev" rel="noopener noreferrer"&gt;&lt;code&gt;spatie/laravel-data&lt;/code&gt;&lt;/a&gt; automatizan el mapeo, y vale la pena mirarlos cuando escribir &lt;code&gt;fromRequest&lt;/code&gt; a mano empiece a doler. Hasta entonces bastan las clases readonly simples.&lt;/p&gt;

&lt;h2&gt;
  
  
  Para qué sirve un Concern
&lt;/h2&gt;

&lt;p&gt;Laravel mismo pone el comportamiento compartido de los modelos en un namespace &lt;code&gt;Concerns&lt;/code&gt;, y el hábito vale la pena copiarlo. Un Concern es un trait que da a muchas clases la misma capacidad pequeña. El artículo del tenant tenía uno bueno, &lt;code&gt;BelongsToCompany&lt;/code&gt;: engancha un scope, rellena una columna y se aplica a todos los modelos que pertenecen a un tenant. Otro podría ser:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;trait&lt;/span&gt; &lt;span class="nc"&gt;Archivable&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;scopeActive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Builder&lt;/span&gt; &lt;span class="nv"&gt;$query&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$query&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;whereNull&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'archived_at'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;archive&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;forceFill&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'archived_at'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Una prueba rápida te dice si algo es un Concern. ¿Puedes nombrarlo como una capacidad, con un prefijo como &lt;code&gt;Has&lt;/code&gt;, &lt;code&gt;Belongs&lt;/code&gt; o un adjetivo como &lt;code&gt;Archivable&lt;/code&gt;? Si el mejor nombre que encuentras es &lt;code&gt;HandlesInvoiceApproval&lt;/code&gt;, es una Action disfrazada de trait.&lt;/p&gt;

&lt;p&gt;El modo de fallo es el cajón de sastre. Un modelo de 3.000 líneas partido en ocho traits sigue siendo un modelo de 3.000 líneas, solo que más difícil de leer, porque los métodos están en ocho archivos y cada trait asume en silencio columnas que viven en otra parte. Tres costos a vigilar:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Acoplamiento oculto: el trait usa &lt;code&gt;$this-&amp;gt;status&lt;/code&gt; sin declarar que lo necesita.&lt;/li&gt;
&lt;li&gt;Colisiones de nombres entre métodos de traits distintos.&lt;/li&gt;
&lt;li&gt;Tests que solo funcionan a través de un modelo que usa el trait.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mantén los Concerns pequeños, con forma de capacidad y aburridos.&lt;/p&gt;

&lt;h2&gt;
  
  
  Events para lo que la Action no debe saber
&lt;/h2&gt;

&lt;p&gt;Volvamos a las cuatro peticiones. Enviar el correo, actualizar el libro mayor y avisar al canal son reacciones a un hecho: una factura fue aprobada. La Action no necesita saber quién reacciona. Anuncia el hecho, y quien le interese escucha.&lt;/p&gt;

&lt;p&gt;Una división útil: lo que debe tener éxito o fallar junto con la aprobación se queda dentro de la transacción de la Action. Lo que puede ocurrir después, o fallar por su cuenta, se vuelve un listener. El correo es un listener. El cambio de estado no.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceApproved&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;ShouldDispatchAfterCommit&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="nc"&gt;Dispatchable&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$invoiceId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;readonly&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$companyId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;La interfaz &lt;code&gt;ShouldDispatchAfterCommit&lt;/code&gt; importa. Según la &lt;a href="https://laravel.com/docs/13.x/events?ref=blog.ifirestone.dev" rel="noopener noreferrer"&gt;documentación de eventos de Laravel&lt;/a&gt;, un evento así no se despacha hasta que la transacción abierta de la base de datos se confirma, y se descarta si la transacción falla. Sin ella, un listener en cola podría correr antes del commit, o enviar un correo por una aprobación que se revirtió.&lt;/p&gt;

&lt;p&gt;La Action lo despacha desde dentro de la transacción, con ids en lugar de modelos, de modo que el payload sea pequeño y explícito:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="nc"&gt;InvoiceApproved&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;dispatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;company_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;El listener es donde vuelve el artículo del tenant. Un listener en cola corre en un worker, sin URL ni usuario, así que con un scope que falla cerrado no tiene empresa. La solución es el middleware de job que ya conocemos, que los listeners también soportan. Esta versión recibe el id en su constructor, porque un listener no puede leerlo del job como hacía el ejemplo anterior:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;RunsAsCompany&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;__construct&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nv"&gt;$companyId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;object&lt;/span&gt; &lt;span class="nv"&gt;$job&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Closure&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runAs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;companyId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;fn&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$job&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SendApprovalEmail&lt;/span&gt; &lt;span class="k"&gt;implements&lt;/span&gt; &lt;span class="nc"&gt;ShouldQueue&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;middleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceApproved&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;array&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;RunsAsCompany&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;companyId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceApproved&lt;/span&gt; &lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$invoice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;findOrFail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$event&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;invoiceId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="nc"&gt;Mail&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;to&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;InvoiceApprovedMail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;La documentación muestra el método &lt;code&gt;middleware&lt;/code&gt; de un listener recibiendo el evento como argumento, y eso es lo que hace que esto funcione. Laravel descubre los listeners escaneando el directorio &lt;code&gt;Listeners&lt;/code&gt; en busca de métodos &lt;code&gt;handle&lt;/code&gt; con un evento tipado, así que no hay paso de registro. Cuando quieras ver el cableado, &lt;code&gt;php artisan event:list&lt;/code&gt; lo imprime.&lt;/p&gt;

&lt;p&gt;El camino completo queda así:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbz4g71xywjayoiraxaks.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbz4g71xywjayoiraxaks.png" alt="Data objects, Concerns y Events: el reparto de apoyo de una Action en Laravel: 04 de 08" width="800" height="164"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Lo que esto te cuesta
&lt;/h2&gt;

&lt;p&gt;Los eventos cambian claridad por desacoplamiento, y la factura llega en cuatro lugares:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Flujo oculto.&lt;/strong&gt; Quien lea &lt;code&gt;ApproveInvoice&lt;/code&gt; no ve el correo. Nombra los eventos en pasado, mantén pocos listeners y usa &lt;code&gt;event:list&lt;/code&gt;. Un evento con un solo listener y sin perspectiva de un segundo es una llamada a un método disfrazada.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Consistencia eventual.&lt;/strong&gt; El correo llega después de la respuesta, y el libro mayor puede ir atrasado. La interfaz tiene que tolerarlo.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Los listeners pueden correr dos veces.&lt;/strong&gt; Las colas reintentan. Haz cada listener idempotente, para que un segundo correo o una segunda fila en el libro mayor no sea posible.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pruebas en dos partes.&lt;/strong&gt; Simula el evento en el test de la Action (&lt;code&gt;Event::fake([InvoiceApproved::class])&lt;/code&gt;) y prueba cada listener por separado.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Los Data objects cuestan una clase por caso de uso. Los Concerns cuestan legibilidad en cuanto se multiplican. Ninguna de las tres es gratis, y ninguna hace falta el día uno.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusión
&lt;/h2&gt;

&lt;p&gt;La Action que derivaba hacia &lt;code&gt;handle(array $data)&lt;/code&gt; ahora recibe un objeto tipado, deja sus capacidades a Concerns pequeños y anuncia lo que pasó en lugar de hacer las tareas de todos. Lo que cambió no es la cantidad de código. Es que cada pieza tiene una razón para existir y una razón para detenerse.&lt;/p&gt;

&lt;p&gt;Para hoy: encuentra una Action con un argumento array y dale un Data object, y encuentra un trait cuyo nombre sea una frase verbal y pregunta si en realidad es una Action. El último artículo de la serie se aparta del código y mira el orden en que un proyecto como este se construye y se entrega de verdad.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>architecture</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Killing Fat Controllers in Laravel: Actions as the Home for Business Logic: 03 of 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Tue, 10 Nov 2026 00:00:00 +0000</pubDate>
      <link>https://dev.to/ifirestone/killing-fat-controllers-in-laravel-actions-as-the-home-for-business-logic-03-of-08-2n4k</link>
      <guid>https://dev.to/ifirestone/killing-fat-controllers-in-laravel-actions-as-the-home-for-business-logic-03-of-08-2n4k</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1772235231771-f17980e811e4%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDl8fHByb2dyYW1taW5nfGVufDB8fHx8MTc5Mjc5MTU2OXww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1772235231771-f17980e811e4%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDl8fHByb2dyYW1taW5nfGVufDB8fHx8MTc5Mjc5MTU2OXww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Killing Fat Controllers in Laravel: Actions as the Home for Business Logic: 03 of 08"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Picture a &lt;code&gt;store&lt;/code&gt; method that begins at line 12 and ends at line 190. It validates the request, loads the invoice, checks that its status allows approval, totals the lines, applies tax, writes an audit row, flips the status, sends an email and returns a redirect. Nobody planned it that way. It grew one reasonable request at a time, and each time the cheapest place for the new rule was the method that already had the request in hand.&lt;/p&gt;

&lt;p&gt;Then the product asks for a bulk approve command for month end, and a few weeks later for an API endpoint. The team now has three options, all bad: copy the logic, call the controller from the command, or fake an HTTP request inside a console job.&lt;/p&gt;

&lt;p&gt;This article follows that one feature, approving an invoice, through the web UI, a console command and an API, to show where the logic should live so that it exists exactly once. It builds on the tenant context from the previous article in the series. Data objects, Concerns and Events come next.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Controllers Get Fat
&lt;/h2&gt;

&lt;p&gt;Fat controllers are rarely a skill problem. They are a gravity problem. A controller method is the first place in the code that holds everything at once: the user, the input, the route-bound models. Logic collects where its inputs already are.&lt;/p&gt;

&lt;p&gt;The price shows up later. Logic trapped behind an HTTP request can't be reused by a command, a queued job or another endpoint. Testing it means booting the whole HTTP stack. And reading it means scrolling past validation and redirects to find the one rule you came for.&lt;/p&gt;

&lt;p&gt;Exhortation won't fix this. Logic needs a better home that has the same inputs, and a controller needs a short list of things it is still allowed to do.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the Controller Is Still Allowed to Do
&lt;/h2&gt;

&lt;p&gt;Four jobs, and only these:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Authorize the request (a policy or a gate).&lt;/li&gt;
&lt;li&gt;Validate the input (a Form Request).&lt;/li&gt;
&lt;li&gt;Call one Action.&lt;/li&gt;
&lt;li&gt;Turn the outcome into an HTTP response.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here is the approval endpoint after the move:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceApprovalController&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Controller&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;store&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nc"&gt;Request&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;Company&lt;/span&gt; &lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt; &lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;RedirectResponse&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Gate&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;authorize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'approve'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;user&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;withErrors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'invoice'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;redirect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;route&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'invoices.show'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One detail that trips people in a company-prefixed app: Laravel hands route parameters to the method in order, so the &lt;code&gt;{company}&lt;/code&gt; from the prefix has to appear in the signature even when the body doesn't need it.&lt;/p&gt;

&lt;p&gt;The method reads in ten seconds. It says who may do this, what happens, and what the user sees when it fails. Nothing in it knows what approving an invoice means.&lt;/p&gt;

&lt;h2&gt;
  
  
  Anatomy of an Action
&lt;/h2&gt;

&lt;p&gt;An Action is a plain class with one public method, named after one use case. No base class is required and Laravel doesn't ship one. The conventions that have worked for me are few:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The class name is a verb phrase: &lt;code&gt;ApproveInvoice&lt;/code&gt;, not &lt;code&gt;InvoiceService&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Dependencies come through the constructor, so the container can build it anywhere.&lt;/li&gt;
&lt;li&gt;The method receives everything it needs as arguments. It never reads the request, the session or &lt;code&gt;auth()-&amp;gt;user()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It owns the transaction.&lt;/li&gt;
&lt;li&gt;It signals business failures with exceptions named after the rule that failed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The same rule from the tenant article applies: nothing reaches for ambient state. The caller says who is approving.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="nv"&gt;$approver&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="no"&gt;DB&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;transaction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$approver&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$invoice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;lockForUpdate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;findOrFail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;PendingApproval&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;because&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
                &lt;span class="s1"&gt;'status'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;Approved&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="s1"&gt;'approved_by'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$approver&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="s1"&gt;'approved_at'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;RuntimeException&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;because&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt; &lt;span class="nv"&gt;$status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"An invoice in status {$status-&amp;gt;value} cannot be approved."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;lockForUpdate&lt;/code&gt; earns its place. If two approvers click at the same second, both requests could read the invoice as pending. Reloading it under a lock inside the transaction, and checking the status after, means the second one fails cleanly. Notice that the reload goes through the tenant scope too, so the Action can't approve another company's invoice even if a caller passes a bad model.&lt;/p&gt;

&lt;p&gt;A &lt;code&gt;null&lt;/code&gt; approver means the system did it. That is a decision about this domain, and it costs a nullable column. Your domain may prefer a dedicated system user.&lt;/p&gt;

&lt;h2&gt;
  
  
  Same Action, Three Doors
&lt;/h2&gt;

&lt;p&gt;Now the month-end command. It has to pick a company explicitly, because a console command has no URL and no logged-in user:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ApproveDueInvoices&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Command&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="nv"&gt;$signature&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'invoices:approve-due {company}'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt; &lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$company&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;where&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'slug'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;argument&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'company'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;firstOrFail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runAs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;where&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'status'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;PendingApproval&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;each&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                        &lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;warn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Skipped {$invoice-&amp;gt;number}: {$e-&amp;gt;getMessage()}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                    &lt;span class="p"&gt;}&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;SUCCESS&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The API endpoint is the controller again with a different ending: it returns a resource or a 409 instead of a redirect. Three doors, three ways of presenting a failure, one rule. When finance changes what "approvable" means, there is one file to edit.&lt;/p&gt;

&lt;h2&gt;
  
  
  Testing Gets Cheaper
&lt;/h2&gt;

&lt;p&gt;The rule now lives where it can be tested without HTTP:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nf"&gt;it&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'approves a pending invoice'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$company&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$invoice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runAs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$pending&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;pendingApproval&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$pending&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;toBe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;Approved&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nf"&gt;it&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'refuses to approve the same invoice twice'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$company&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runAs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$approved&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;approved&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$approved&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;throws&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The factory states &lt;code&gt;pendingApproval()&lt;/code&gt; and &lt;code&gt;approved()&lt;/code&gt; are assumed here. What matters is the split: the rules are tested once, at the Action. The controller test only has to prove the wiring. Guests are redirected, non-approvers get a 403, and a failure comes back as a validation error.&lt;/p&gt;

&lt;h2&gt;
  
  
  When an Action Is Too Much
&lt;/h2&gt;

&lt;p&gt;This pattern has costs, and they are real. Each Action is a file, a name and a hop for the reader. Applied everywhere, it turns a plain &lt;code&gt;update&lt;/code&gt; of a customer's phone number into ceremony.&lt;/p&gt;

&lt;p&gt;Three smells tell you it has gone too far, or not far enough:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Pass-through Actions.&lt;/strong&gt; If &lt;code&gt;handle&lt;/code&gt; is one Eloquent call, the Action adds a file and removes nothing. Keep simple CRUD in the controller.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Actions calling Actions.&lt;/strong&gt; A little is fine. A chain of five becomes a hidden call graph that is harder to follow than the fat controller was. Compose in one higher-level Action instead, and keep it readable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A &lt;code&gt;handle&lt;/code&gt; with eight parameters.&lt;/strong&gt; The inputs want to be a typed object. That is the next article.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It is also worth saying what an Action is not. An &lt;code&gt;InvoiceService&lt;/code&gt; with twelve methods is the fat controller moved one folder over. The discipline is in one use case per class.&lt;/p&gt;

&lt;p&gt;My rule of thumb is to extract an Action when a second caller appears, or when a controller method stops fitting on one screen. Before that, the extra indirection costs more than it returns.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The 190-line method didn't need cleverer code. It needed the rule to live somewhere that a controller, a command and an endpoint could all call, and a controller that was allowed to do four small things. Pick the fattest method in your app, find the rule that already has a second caller, and extract only that one.&lt;/p&gt;

&lt;p&gt;In the next article we deal with what still feels messy around an Action: the array of loose inputs, the traits that become junk drawers, and the emails and ledger updates that don't belong inside the transaction.&lt;/p&gt;

</description>
      <category>backend</category>
      <category>database</category>
      <category>laravel</category>
      <category>saas</category>
    </item>
    <item>
      <title>Adiós a los controladores gordos en Laravel: las Actions como hogar de la lógica de negocio: 03 de 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Fri, 06 Nov 2026 13:00:00 +0000</pubDate>
      <link>https://dev.to/ifirestone/adios-a-los-controladores-gordos-en-laravel-las-actions-como-hogar-de-la-logica-de-negocio-03-de-43p3</link>
      <guid>https://dev.to/ifirestone/adios-a-los-controladores-gordos-en-laravel-las-actions-como-hogar-de-la-logica-de-negocio-03-de-43p3</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Por qué engordan los controladores, cómo mover las reglas de negocio a clases Action de un solo propósito, cómo es una buena Action y cuándo el patrón cuesta más de lo que da. Una funcionalidad de facturas, tres puntos de entrada.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1768293336571-c48f8765a82d%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDN8fHNhYXN8ZW58MHx8fHwxNzkyNzg2NjMwfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1768293336571-c48f8765a82d%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDN8fHNhYXN8ZW58MHx8fHwxNzkyNzg2NjMwfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Adiós a los controladores gordos en Laravel: las Actions como hogar de la lógica de negocio: 03 de 08"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Imagina un método &lt;code&gt;store&lt;/code&gt; que empieza en la línea 12 y termina en la 190. Valida la petición, carga la factura, comprueba que su estado permite aprobarla, suma las líneas, aplica impuestos, escribe una fila de auditoría, cambia el estado, envía un correo y devuelve una redirección. Nadie lo planeó así. Creció con una petición razonable a la vez, y cada vez el lugar más barato para la regla nueva era el método que ya tenía la petición en la mano.&lt;/p&gt;

&lt;p&gt;Luego producto pide un comando de aprobación masiva para el cierre de mes, y unas semanas después un endpoint de API. El equipo tiene ahora tres opciones, todas malas: copiar la lógica, llamar al controlador desde el comando o simular una petición HTTP dentro de un job de consola.&lt;/p&gt;

&lt;p&gt;Este artículo sigue esa única funcionalidad, aprobar una factura, a través de la interfaz web, un comando de consola y una API, para mostrar dónde debe vivir la lógica de modo que exista exactamente una vez. Se apoya en el contexto de tenant del artículo anterior de la serie. Data objects, Concerns y Events vienen después.&lt;/p&gt;

&lt;h2&gt;
  
  
  Por qué engordan los controladores
&lt;/h2&gt;

&lt;p&gt;Los controladores gordos rara vez son un problema de habilidad. Son un problema de gravedad. Un método de controlador es el primer lugar del código que lo tiene todo a la vez: el usuario, la entrada, los modelos enlazados por la ruta. La lógica se acumula donde ya están sus entradas.&lt;/p&gt;

&lt;p&gt;El precio aparece después. La lógica atrapada detrás de una petición HTTP no la puede reutilizar un comando, un job en cola ni otro endpoint. Probarla significa levantar toda la pila HTTP. Y leerla significa pasar por encima de validaciones y redirecciones para encontrar la única regla que viniste a buscar.&lt;/p&gt;

&lt;p&gt;Las exhortaciones no arreglan esto. La lógica necesita un hogar mejor con las mismas entradas, y el controlador necesita una lista corta de cosas que aún puede hacer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Lo que el controlador todavía puede hacer
&lt;/h2&gt;

&lt;p&gt;Cuatro trabajos, y solo estos:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Autorizar la petición (una policy o un gate).&lt;/li&gt;
&lt;li&gt;Validar la entrada (un Form Request).&lt;/li&gt;
&lt;li&gt;Llamar a una Action.&lt;/li&gt;
&lt;li&gt;Convertir el resultado en una respuesta HTTP.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Así queda el endpoint de aprobación después de la mudanza:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceApprovalController&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Controller&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;store&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nc"&gt;Request&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;Company&lt;/span&gt; &lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt; &lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;RedirectResponse&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Gate&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;authorize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'approve'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;user&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;back&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;withErrors&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'invoice'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;getMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;redirect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;route&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'invoices.show'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Un detalle que enreda a la gente en una app con prefijo de empresa: Laravel entrega los parámetros de la ruta al método en orden, así que el &lt;code&gt;{company}&lt;/code&gt; del prefijo tiene que aparecer en la firma aunque el cuerpo no lo necesite.&lt;/p&gt;

&lt;p&gt;El método se lee en diez segundos. Dice quién puede hacerlo, qué ocurre y qué ve el usuario cuando falla. Nada en él sabe qué significa aprobar una factura.&lt;/p&gt;

&lt;h2&gt;
  
  
  Anatomía de una Action
&lt;/h2&gt;

&lt;p&gt;Una Action es una clase simple con un método público, nombrada según un caso de uso. No hace falta una clase base y Laravel no incluye ninguna. Las convenciones que me han funcionado son pocas:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;El nombre de la clase es una frase verbal: &lt;code&gt;ApproveInvoice&lt;/code&gt;, no &lt;code&gt;InvoiceService&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Las dependencias llegan por el constructor, así el container puede construirla en cualquier parte.&lt;/li&gt;
&lt;li&gt;El método recibe todo lo que necesita como argumentos. Nunca lee la petición, la sesión ni &lt;code&gt;auth()-&amp;gt;user()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Es dueña de la transacción.&lt;/li&gt;
&lt;li&gt;Señala los fallos de negocio con excepciones nombradas según la regla que falló.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Vale la misma regla del artículo del tenant: nada busca estado ambiental. Quien llama dice quién está aprobando.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="nc"&gt;User&lt;/span&gt; &lt;span class="nv"&gt;$approver&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="no"&gt;DB&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;transaction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$approver&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nv"&gt;$invoice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;lockForUpdate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;findOrFail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;PendingApproval&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;because&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
                &lt;span class="s1"&gt;'status'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;Approved&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="s1"&gt;'approved_by'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nv"&gt;$approver&lt;/span&gt;&lt;span class="o"&gt;?-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="s1"&gt;'approved_at'&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;final&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;RuntimeException&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;because&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt; &lt;span class="nv"&gt;$status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Una factura en estado {$status-&amp;gt;value} no puede aprobarse."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;El &lt;code&gt;lockForUpdate&lt;/code&gt; se gana su lugar. Si dos aprobadores hacen clic en el mismo segundo, ambas peticiones podrían leer la factura como pendiente. Recargarla bajo un bloqueo dentro de la transacción, y comprobar el estado después, hace que la segunda falle limpiamente. Fíjate en que la recarga también pasa por el scope del tenant, así que la Action no puede aprobar la factura de otra empresa aunque quien la llame pase un modelo equivocado.&lt;/p&gt;

&lt;p&gt;Un aprobador &lt;code&gt;null&lt;/code&gt; significa que lo hizo el sistema. Es una decisión sobre este dominio, y cuesta una columna nullable. Tu dominio puede preferir un usuario de sistema dedicado.&lt;/p&gt;

&lt;h2&gt;
  
  
  La misma Action, tres puertas
&lt;/h2&gt;

&lt;p&gt;Ahora el comando de cierre de mes. Tiene que elegir una empresa de forma explícita, porque un comando de consola no tiene URL ni usuario con sesión:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;ApproveDueInvoices&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;Command&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="nv"&gt;$signature&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'invoices:approve-due {company}'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt; &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt; &lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$company&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;where&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'slug'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;argument&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'company'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;firstOrFail&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="nv"&gt;$tenant&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runAs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;where&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'status'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;PendingApproval&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;each&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;use&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                        &lt;span class="nv"&gt;$approve&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt; &lt;span class="nv"&gt;$e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                        &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;warn&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Omitida {$invoice-&amp;gt;number}: {$e-&amp;gt;getMessage()}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
                    &lt;span class="p"&gt;}&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kt"&gt;self&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="no"&gt;SUCCESS&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;El endpoint de API es el controlador otra vez con un final distinto: devuelve un recurso o un 409 en lugar de una redirección. Tres puertas, tres formas de presentar un fallo, una regla. Cuando finanzas cambie lo que significa "aprobable", hay un solo archivo que editar.&lt;/p&gt;

&lt;h2&gt;
  
  
  Probar sale más barato
&lt;/h2&gt;

&lt;p&gt;La regla ahora vive donde se puede probar sin HTTP:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nf"&gt;it&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'aprueba una factura pendiente'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$company&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nv"&gt;$invoice&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runAs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$pending&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;pendingApproval&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$pending&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$invoice&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;toBe&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceStatus&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nc"&gt;Approved&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nf"&gt;it&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'se niega a aprobar dos veces la misma factura'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$company&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Company&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;TenantContext&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runAs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$company&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$approved&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;factory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;approved&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

        &lt;span class="nf"&gt;app&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;ApproveInvoice&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$approved&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;throws&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InvoiceCannotBeApproved&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Los estados de factory &lt;code&gt;pendingApproval()&lt;/code&gt; y &lt;code&gt;approved()&lt;/code&gt; se dan por supuestos aquí. Lo que importa es la división: las reglas se prueban una sola vez, en la Action. El test del controlador solo tiene que demostrar el cableado. Los invitados son redirigidos, los que no pueden aprobar reciben un 403 y un fallo vuelve como error de validación.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cuando una Action es demasiado
&lt;/h2&gt;

&lt;p&gt;Este patrón tiene costos, y son reales. Cada Action es un archivo, un nombre y un salto para el lector. Aplicada en todas partes, convierte un simple &lt;code&gt;update&lt;/code&gt; del teléfono de un cliente en ceremonia.&lt;/p&gt;

&lt;p&gt;Tres señales te dicen que te pasaste, o que te quedaste corto:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Actions de paso.&lt;/strong&gt; Si &lt;code&gt;handle&lt;/code&gt; es una sola llamada a Eloquent, la Action añade un archivo y no quita nada. Deja el CRUD simple en el controlador.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Actions que llaman a Actions.&lt;/strong&gt; Un poco está bien. Una cadena de cinco se vuelve un grafo de llamadas oculto más difícil de seguir que el controlador gordo. Mejor compone en una Action de nivel superior y manténla legible.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Un &lt;code&gt;handle&lt;/code&gt; con ocho parámetros.&lt;/strong&gt; Las entradas piden ser un objeto tipado. Eso es el siguiente artículo.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;También vale decir lo que una Action no es. Un &lt;code&gt;InvoiceService&lt;/code&gt; con doce métodos es el controlador gordo movido una carpeta más allá. La disciplina está en un caso de uso por clase.&lt;/p&gt;

&lt;p&gt;Mi regla práctica es extraer una Action cuando aparece un segundo llamador, o cuando un método de controlador deja de caber en una pantalla. Antes de eso, la indirección extra cuesta más de lo que devuelve.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusión
&lt;/h2&gt;

&lt;p&gt;El método de 190 líneas no necesitaba código más ingenioso. Necesitaba que la regla viviera en un lugar al que un controlador, un comando y un endpoint pudieran llamar, y un controlador al que solo se le permitieran cuatro cosas pequeñas. Elige el método más gordo de tu app, encuentra la regla que ya tiene un segundo llamador y extrae solo esa.&lt;/p&gt;

&lt;p&gt;En el siguiente artículo abordamos lo que todavía se siente desordenado alrededor de una Action: el array de entradas sueltas, los traits que se vuelven cajón de sastre y los correos y actualizaciones de libro mayor que no pertenecen dentro de la transacción.&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>architecture</category>
      <category>backend</category>
    </item>
    <item>
      <title>Multi-Tenant SaaS in Laravel: One Database, a Global Scope, and the Leaks It Doesn't Catch: 02 of 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Thu, 05 Nov 2026 13:00:06 +0000</pubDate>
      <link>https://dev.to/ifirestone/multi-tenant-saas-in-laravel-one-database-a-global-scope-and-the-leaks-it-doesnt-catch-02-of-08-41fd</link>
      <guid>https://dev.to/ifirestone/multi-tenant-saas-in-laravel-one-database-a-global-scope-and-the-leaks-it-doesnt-catch-02-of-08-41fd</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1563986768609-322da13575f3%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDJ8fHNhYXN8ZW58MHx8fHwxNzkyNzkxMTIxfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1563986768609-322da13575f3%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDJ8fHNhYXN8ZW58MHx8fHwxNzkyNzkxMTIxfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Multi-Tenant SaaS in Laravel: One Database, a Global Scope, and the Leaks It Doesn't Catch: 02 of 08" width="2000" height="1333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Imagine a team that ships an invoicing SaaS in three months. Every query carries a &lt;code&gt;where('company_id', $companyId)&lt;/code&gt;, reviewers look for it in every pull request, and for half a year nothing goes wrong. Then someone adds a nightly job that emails overdue reminders. The scheduler runs it, so there is no logged-in user, and the helper that used to supply the company id returns null. The query loses its filter without a sound, and the job reads every company's invoices.&lt;/p&gt;
&lt;p&gt;Nothing in that story is exotic. It is what happens when tenant isolation depends on every developer remembering one line, and on a request context that jobs and commands don't have.&lt;/p&gt;
&lt;p&gt;This article is about isolating companies inside one Laravel app: which tenancy model to pick, how to resolve the current company, how to enforce it so that forgetting becomes impossible, and how to test it. How to organize the business logic itself (Actions, Data objects, Events) belongs to the next articles in the series.&lt;/p&gt;
&lt;h2 id="three-ways-to-give-every-company-its-own-space"&gt;Three Ways to Give Every Company Its Own Space&lt;/h2&gt;
&lt;p&gt;The first decision is where each company's data physically lives. There are three common answers.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Model&lt;/th&gt;
&lt;th&gt;What keeps tenants apart&lt;/th&gt;
&lt;th&gt;What it costs&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Shared database, &lt;code&gt;company_id&lt;/code&gt; column&lt;/td&gt;
&lt;td&gt;Your code, optionally backed by row-level security in the database&lt;/td&gt;
&lt;td&gt;Cheapest to run: one migration, one connection pool, one backup. Isolation is only as good as your discipline&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Schema per company (PostgreSQL)&lt;/td&gt;
&lt;td&gt;The database schema&lt;/td&gt;
&lt;td&gt;A real boundary, but every migration runs once per schema and each request has to switch schema&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Database per company&lt;/td&gt;
&lt;td&gt;The database server&lt;/td&gt;
&lt;td&gt;Strongest isolation and per-company restore, but migrations, connections and the bill grow with every new customer&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;For a product that is still looking for its market, I would start with the shared database. It echoes the argument in &lt;a href="https://dev.to/ifirestone/modular-monolith-or-microservices-a-framework-for-deciding-without-dogma-4ppa"&gt;Modular Monolith or Microservices: A Framework for Deciding Without Dogma&lt;/a&gt;: the cheaper option usually gives most of the benefit, as long as you keep the exit open. The price is that isolation now lives in your code. The rest of this article is about making that code hard to bypass.&lt;/p&gt;
&lt;h2 id="the-url-decides-who-the-tenant-is"&gt;The URL Decides Who the Tenant Is&lt;/h2&gt;
&lt;p&gt;Next question: how does a request say which company it belongs to? A subdomain, a header, the session, a path segment. The tempting option is a "current company" column on the user. Switch once, and every later request just knows. It breaks the moment someone opens two tabs. The column holds one answer per user, the tabs want two, and whichever switched last wins for both.&lt;/p&gt;
&lt;p&gt;I prefer the path: &lt;code&gt;/{company-slug}/invoices&lt;/code&gt;. The URL is the only state that belongs to the request itself. It survives bookmarks and shared links, and it puts the tenant in your logs.&lt;/p&gt;
&lt;p&gt;A middleware resolves the slug, checks membership and opens the tenant context for the rest of the request.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class ResolveCompany
{
    public function __construct(private TenantContext $tenant) {}

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request-&amp;gt;user() ?? throw new AuthenticationException;

        // Bindings have not run yet, so this is still the raw slug.
        $company = Company::where('slug', $request-&amp;gt;route('company'))-&amp;gt;first();

        abort_if(
            $company === null || ! $user-&amp;gt;companies()-&amp;gt;whereKey($company-&amp;gt;id)-&amp;gt;exists(),
            404,
        );

        return $this-&amp;gt;tenant-&amp;gt;runAs($company-&amp;gt;id, fn () =&amp;gt; $next($request));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I return 404 for non-members so the URL doesn't confirm that a company exists. A 403 is friendlier to a legitimate user who mistyped, so pick one on purpose.&lt;/p&gt;
&lt;p&gt;There is one trap, and it is about order. Route model binding happens in &lt;code&gt;SubstituteBindings&lt;/code&gt;, and when &lt;code&gt;{invoice}&lt;/code&gt; gets bound, that query goes through the model's global scopes. If the tenant isn't set by then, binding runs unscoped. In Laravel's default &lt;a href="https://laravel.com/docs/13.x/middleware" rel="noopener noreferrer"&gt;middleware priority list&lt;/a&gt; that middleware also sits before authentication, which is why the code above reads the user itself. Move the tenant middleware ahead of bindings in &lt;code&gt;bootstrap/app.php&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-&amp;gt;withMiddleware(function (Middleware $middleware): void {
    $middleware-&amp;gt;prependToPriorityList(
        before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
        prepend: \App\Http\Middleware\ResolveCompany::class,
    );
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And the routes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Route::middleware(['auth', ResolveCompany::class])
    -&amp;gt;prefix('{company}')
    -&amp;gt;group(function () {
        Route::resource('invoices', InvoiceController::class);
    });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The middleware calls something named &lt;code&gt;TenantContext&lt;/code&gt;. That is the next piece, and the one the nightly job will need.&lt;/p&gt;
&lt;h2 id="one-place-that-knows-the-current-company"&gt;One Place That Knows the Current Company&lt;/h2&gt;
&lt;p&gt;The fix for the opening story starts with a rule: nothing reads the company id from &lt;code&gt;auth()-&amp;gt;user()&lt;/code&gt;. Everything asks one small object, and anyone who wants to run code as a company has to say so out loud.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;final class TenantContext
{
    private ?int $companyId = null;

    public function id(): ?int
    {
        return $this-&amp;gt;companyId;
    }

    public function runAs(int $companyId, Closure $callback): mixed
    {
        $previous = $this-&amp;gt;companyId;
        $this-&amp;gt;companyId = $companyId;

        try {
            return $callback();
        } finally {
            $this-&amp;gt;companyId = $previous;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Register it with &lt;code&gt;scoped&lt;/code&gt;, not &lt;code&gt;singleton&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$this-&amp;gt;app-&amp;gt;scoped(TenantContext::class);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Per the &lt;a href="https://laravel.com/docs/13.x/container" rel="noopener noreferrer"&gt;container docs&lt;/a&gt;, scoped instances are flushed when an Octane worker takes a new request or a queue worker takes a new job. A plain singleton would carry the previous tenant into the next unit of work, which is the same leak in a different costume. The &lt;code&gt;finally&lt;/code&gt; block is a second line of defense for the case where code calls &lt;code&gt;runAs&lt;/code&gt; and throws.&lt;/p&gt;
&lt;h2 id="a-scope-that-fails-closed"&gt;A Scope That Fails Closed&lt;/h2&gt;
&lt;p&gt;Now the part everyone writes first. A &lt;a href="https://laravel.com/docs/13.x/eloquent" rel="noopener noreferrer"&gt;global scope&lt;/a&gt; filters every query for a model, and a trait can attach it and fill &lt;code&gt;company_id&lt;/code&gt; on create. The difference from the usual version is what happens when there is no company: it throws instead of skipping the filter.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class TenantScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $companyId = app(TenantContext::class)-&amp;gt;id()
            ?? throw new MissingTenantContext($model::class);

        $builder-&amp;gt;where($model-&amp;gt;qualifyColumn('company_id'), $companyId);
    }
}

trait BelongsToCompany
{
    public static function bootBelongsToCompany(): void
    {
        static::addGlobalScope(new TenantScope);

        static::creating(function (Model $model): void {
            $model-&amp;gt;company_id ??= app(TenantContext::class)-&amp;gt;id()
                ?? throw new MissingTenantContext($model::class);
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Pair it with a migration where the column cannot be null and company comes first in the indexes, since nearly every query filters by it:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$table-&amp;gt;foreignId('company_id')-&amp;gt;constrained();
$table-&amp;gt;string('number');
$table-&amp;gt;unique(['company_id', 'number']);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The cost of failing closed is real. Admin screens, seeders, reports across all companies and anything else that legitimately needs unscoped data must say so with &lt;code&gt;Invoice::withoutGlobalScope(TenantScope::class)&lt;/code&gt;. I count that as a feature. Every unscoped query is now a line you can grep for in code review, and the list should stay short.&lt;/p&gt;
&lt;p&gt;A scope also has blind spots, and it is worth knowing them before trusting it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;DB::table('invoices')&lt;/code&gt; and raw SQL never see Eloquent scopes.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;unique&lt;/code&gt; and &lt;code&gt;exists&lt;/code&gt; validation rules query the table directly, so they ignore the scope. Add the condition yourself: &lt;code&gt;Rule::unique('invoices', 'number')-&amp;gt;where('company_id', $companyId)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Anything that crosses a model that doesn't use the trait is only as safe as that other model.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="the-nightly-job-again"&gt;The Nightly Job, Again&lt;/h2&gt;
&lt;p&gt;Back to the reminder job. Under the new rules it can't run as it was written, because nothing sets the company. So the job takes the company explicitly and a job middleware opens the context around it. Job middleware, described in the &lt;a href="https://laravel.com/docs/13.x/queues" rel="noopener noreferrer"&gt;queues docs&lt;/a&gt;, wraps the job the way route middleware wraps a request.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class RunsAsCompany
{
    public function handle(object $job, Closure $next): void
    {
        app(TenantContext::class)-&amp;gt;runAs($job-&amp;gt;companyId, fn () =&amp;gt; $next($job));
    }
}

class SendOverdueReminders implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $companyId) {}

    public function middleware(): array
    {
        return [new RunsAsCompany];
    }

    public function handle(): void
    {
        // Invoice::query() is now filtered to $this-&amp;gt;companyId
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The scheduler fans out one job per company:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Schedule::call(function () {
    Company::query()-&amp;gt;each(
        fn (Company $company) =&amp;gt; SendOverdueReminders::dispatch($company-&amp;gt;id)
    );
})-&amp;gt;dailyAt('02:00');
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is a cost: N jobs instead of one. In return, a slow or failing company can't block the others, retries stay inside one tenant, and the tenant is visible in the payload instead of hidden in ambient state. &lt;code&gt;Company&lt;/code&gt; itself doesn't use the trait, because it is the tenant.&lt;/p&gt;
&lt;h2 id="companies-users-and-roles"&gt;Companies, Users and Roles&lt;/h2&gt;
&lt;p&gt;In a multi-company product, one person often belongs to several companies. That settles where the role lives. It belongs to the membership, a &lt;code&gt;company_user&lt;/code&gt; pivot with a &lt;code&gt;role&lt;/code&gt; column, and not to the user. The same person can be an admin in one company and a viewer in another, and the middleware already knows which company the request is about.&lt;/p&gt;
&lt;p&gt;The temptation is to give roles a rank and compare numbers. It works for a while. Permissions as plain strings per role (&lt;code&gt;invoice:create&lt;/code&gt;, &lt;code&gt;invoice:void&lt;/code&gt;) age better, because the day someone asks for a role that can void invoices but not edit them, you add a row instead of reshuffling a hierarchy. Check them with Laravel's policies, and pass the membership role, not a user-level flag.&lt;/p&gt;
&lt;h2 id="prove-it-with-a-test-that-tries-to-leak"&gt;Prove It With a Test That Tries to Leak&lt;/h2&gt;
&lt;p&gt;A scope you haven't attacked is a scope you hope works. Three tests cover the story so far, written with Pest:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;it('never returns another company\'s invoices', function () {
    $acme = Company::factory()-&amp;gt;create();
    $globex = Company::factory()-&amp;gt;create();
    $tenant = app(TenantContext::class);

    $tenant-&amp;gt;runAs($globex-&amp;gt;id, fn () =&amp;gt; Invoice::factory()-&amp;gt;create());

    expect($tenant-&amp;gt;runAs($acme-&amp;gt;id, fn () =&amp;gt; Invoice::count()))-&amp;gt;toBe(0);
});

it('refuses to query without a tenant', function () {
    Invoice::count();
})-&amp;gt;throws(MissingTenantContext::class);

it('returns 404 for a company the user does not belong to', function () {
    $other = Company::factory()-&amp;gt;create();

    $this-&amp;gt;actingAs(User::factory()-&amp;gt;create())
        -&amp;gt;get("/{$other-&amp;gt;slug}/invoices")
        -&amp;gt;assertNotFound();
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The second test is the one that would have caught the opening story. Once these exist, add a guard that lists every table with a &lt;code&gt;company_id&lt;/code&gt; column and fails if its model doesn't use the trait. New tables are where leaks are born.&lt;/p&gt;
&lt;h2 id="where-shared-schema-stops-working"&gt;Where Shared Schema Stops Working&lt;/h2&gt;
&lt;p&gt;This design has limits, and it is better to see them early. A single large tenant can dominate the indexes and the connection pool, so noisy neighbors are a real possibility. Restoring one company from a backup means extracting its rows from a backup of everyone. And some customers, especially enterprise or regulated ones, will ask for their own database no matter how good your scope is.&lt;/p&gt;
&lt;p&gt;The design also leaves you an exit. Because every query goes through one context and one trait, moving a big customer to its own database later is a much smaller refactor than it would be in a codebase full of hand-written &lt;code&gt;where&lt;/code&gt; clauses. That is the argument for doing it this way even if you never need the exit.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The nightly job that emailed the wrong customers did not need a cleverer filter. It needed a system where running without a company is an error, and where the error shows up in a test long before a customer sees it. Resolve the tenant from the URL, keep it in one place, make the scope fail closed, and try to leak on purpose.&lt;/p&gt;
&lt;p&gt;If you want an action for today, grep your codebase for &lt;code&gt;auth()-&amp;gt;user()-&amp;gt;company_id&lt;/code&gt; and &lt;code&gt;withoutGlobalScopes&lt;/code&gt;, and write the "refuses to query without a tenant" test. In the next article we leave isolation behind and look at where the business logic should live so that controllers stay thin.&lt;/p&gt;

</description>
      <category>backend</category>
      <category>database</category>
      <category>laravel</category>
      <category>saas</category>
    </item>
    <item>
      <title>De pantallas verdes a contenedores: pasar de AS/400 e IBM ACE a microservicios</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Wed, 04 Nov 2026 13:00:06 +0000</pubDate>
      <link>https://dev.to/ifirestone/de-pantallas-verdes-a-contenedores-pasar-de-as400-e-ibm-ace-a-microservicios-31dh</link>
      <guid>https://dev.to/ifirestone/de-pantallas-verdes-a-contenedores-pasar-de-as400-e-ibm-ace-a-microservicios-31dh</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fez831nr4xj57emvtmv1j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fez831nr4xj57emvtmv1j.png" alt="De pantallas verdes a contenedores: pasar de AS/400 e IBM ACE a microservicios" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;blockquote&gt;Llevar una arquitectura empresarial de RPG en AS/400 e IBM App Connect Enterprise (ACE) a microservicios nativos de nube es menos una reescritura y más una evolución operativa. Así se recorre ese camino.&lt;/blockquote&gt;
&lt;h2 id="la-pantalla-verde-en-la-era-de-kubernetes"&gt;La pantalla verde en la era de Kubernetes&lt;/h2&gt;
&lt;p&gt;Durante décadas, la columna vertebral de la computación empresarial corrió sobre hierro confiable y sólido como una roca. En muchas organizaciones de banca, seguros y logística, la lógica de negocio central sigue viviendo dentro de un IBM AS/400 (Power Systems / IBM i) que ejecuta programas RPG, acoplado a un bus de servicios empresarial (ESB) como IBM App Connect Enterprise (ACE) o su predecesor, Message Broker, que enruta y transforma mensajes por toda la empresa.&lt;/p&gt;
&lt;p&gt;Para los equipos que los construyeron y los mantienen, estos sistemas son maravillas de estabilidad. Un solo equipo AS/400 puede funcionar años sin reiniciarse, procesando millones de transacciones con un rendimiento predecible.&lt;/p&gt;
&lt;p&gt;Luego llega el mandato de la dirección: &lt;em&gt;"Necesitamos modernizarnos. Nos vamos a microservicios y Kubernetes."&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;De pronto, desarrolladores que pasaron veinte años dominando subrutinas RPG, definiciones de pantallas DDS y flujos de mensajes ESQL en ACE se encuentran mirando Dockerfiles, manifiestos YAML y arquitecturas asíncronas dirigidas por eventos. El reto no es solo aprender un lenguaje nuevo; es desaprender décadas de paradigmas centralizados y fuertemente acoplados.&lt;/p&gt;
&lt;p&gt;Esta es una forma de tender el puente entre AS/400, IBM ACE y los microservicios nativos de nube modernos sin romper la continuidad del negocio que mantiene viva a la empresa.&lt;/p&gt;
&lt;h2 id="fase-1-entender-el-mundo-viejo-y-por-qu%C3%A9-cuesta-dejarlo"&gt;Fase 1: entender el mundo viejo (y por qué cuesta dejarlo)&lt;/h2&gt;
&lt;p&gt;Para migrar con éxito fuera de un AS/400 y de un ESB empresarial, primero hay que entender qué problemas resolvían originalmente y por qué replicar esas funciones en un sistema distribuido es complicado.&lt;/p&gt;
&lt;h3 id="1-el-poder-monol%C3%ADtico-de-rpg-y-db2400"&gt;1. El poder monolítico de RPG y DB2/400&lt;/h3&gt;
&lt;p&gt;En el AS/400, la base de datos (DB2 for i) y el código de la aplicación (RPG) están profundamente entrelazados. Las llamadas de programa a programa se ejecutan en memoria, sin sobrecarga de red. El bloqueo a nivel de registro y la integridad transaccional los maneja de forma nativa el sistema operativo.&lt;/p&gt;
&lt;p&gt;Cuando descompones un monolito RPG en microservicios, pierdes ese rendimiento en memoria que antes era gratis. Lo que era una simple llamada a una subrutina local pasa a ser una llamada REST o un mensaje asíncrono por la red, con sobrecarga de serialización, latencia y modos de fallo nuevos.&lt;/p&gt;
&lt;h3 id="2-la-trampa-del-esb-ibm-ace-como-cuello-de-botella"&gt;2. La trampa del ESB: IBM ACE como cuello de botella&lt;/h3&gt;
&lt;p&gt;IBM App Connect Enterprise (ACE) e IBM Message Broker son motores potentes para traducir protocolos, enrutar mensajes y transformar datos con ESQL. Sin embargo, en muchas organizaciones el ESB pasó de ser una capa de integración a convertirse en un &lt;strong&gt;centro de integración monolítico&lt;/strong&gt;, con lógica de negocio compleja, consultas a bases de datos y gestión de estado.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;       [ AS/400 / RPG ]&lt;br&gt;
              │&lt;br&gt;
              ▼ (MQ / DataQueues)&lt;br&gt;
      [ IBM ACE (ESB) ] ◄─── Lógica de negocio que se filtra&lt;br&gt;
              │&lt;br&gt;
              ▼&lt;br&gt;
    [ Sistemas downstream ]&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Cuando todo pasa por un ESB central, este se convierte en un punto único de fallo y en un cuello de botella de despliegue. Cada cambio menor exige coordinar despliegues en todo el bus empresarial.&lt;/p&gt;
&lt;h2 id="fase-2-traducir-los-conceptos-legacy-a-paradigmas-nativos-de-nube"&gt;Fase 2: traducir los conceptos legacy a paradigmas nativos de nube&lt;/h2&gt;
&lt;p&gt;Dejar estas plataformas no significa tirar a la basura tu conocimiento del dominio. La mayoría de los patrones arquitectónicos centrales tienen equivalentes modernos directos:&lt;/p&gt;


&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Concepto legacy (AS/400 / ACE)&lt;/th&gt;
&lt;th&gt;Equivalente en microservicios&lt;/th&gt;
&lt;th&gt;¿Qué cambia?&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;DataQueues / MQ&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Brokers de eventos (Kafka, RabbitMQ, Redis)&lt;/td&gt;
&lt;td&gt;La mensajería asíncrona pasa de colas propietarias a logs de eventos distribuidos y escalables.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Transformaciones de datos en ESQL&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Servicios de dominio / transformadores de API&lt;/td&gt;
&lt;td&gt;La lógica de transformación centralizada se traslada a microservicios de dominio o a API gateways ligeros.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Planificación de jobs a nivel de SO&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Kubernetes CronJobs / planificadores distribuidos&lt;/td&gt;
&lt;td&gt;Los flujos de jobs del AS/400 (&lt;code&gt;JOBD&lt;/code&gt;, &lt;code&gt;SBMJOB&lt;/code&gt;) se reemplazan por workers en contenedores y orquestadores.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Transacciones nativas de DB2/400&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Patrón Saga / consistencia eventual&lt;/td&gt;
&lt;td&gt;Las transacciones atómicas entre dominios se reemplazan por transacciones compensatorias coreografiadas u orquestadas.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;


&lt;h2 id="fase-3-la-estrategia-de-migraci%C3%B3n-la-higuera-estranguladora-en-acci%C3%B3n"&gt;Fase 3: la estrategia de migración (la higuera estranguladora en acción)&lt;/h2&gt;
&lt;p&gt;No puedes reescribir un núcleo AS/400 de la noche a la mañana. El negocio depende de él para operar cada día. En lugar de eso, usa una estrategia de extracción por fases.&lt;/p&gt;
&lt;h3 id="paso-1-envolver-y-exponer-modernizar-los-bordes"&gt;Paso 1: envolver y exponer (modernizar los bordes)&lt;/h3&gt;
&lt;p&gt;Antes de mover cualquier código fuera del AS/400, expón sus capacidades centrales como APIs modernas. Puedes usar herramientas como los IBM WebSphere Adapters, envoltorios REST escritos en RPG o capas de proxy ligeras.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Trata el AS/400 como un servicio legacy respaldado por una base de datos.&lt;/li&gt;
&lt;li&gt;Construye tu nuevo frontend nativo de nube y los microservicios de apoyo (por ejemplo, en Node.js, Go o Java/Spring Boot) para que consuman esas APIs.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="paso-2-sacar-la-integraci%C3%B3n-de-ace"&gt;Paso 2: sacar la integración de ACE&lt;/h3&gt;
&lt;p&gt;Si tus flujos de IBM ACE están cargados de lógica de negocio, empieza a quitarles esas responsabilidades. Saca las reglas de validación y transformación de ESQL y llévalas a microservicios, dejando a ACE estrictamente como puente de protocolos, si todavía hace falta para hablar con los endpoints de los sistemas legacy.&lt;/p&gt;
&lt;h3 id="paso-3-extraer-dominio-por-dominio"&gt;Paso 3: extraer dominio por dominio&lt;/h3&gt;
&lt;p&gt;Identifica los contextos acotados que cambian con frecuencia, como las notificaciones a clientes, los reportes o la lógica auxiliar de facturación, y reescríbelos por completo como microservicios. Las operaciones de lectura suelen poder migrarse primero, replicando los datos de DB2/400 a una base de datos de lectura moderna con herramientas de Change Data Capture (CDC).&lt;/p&gt;
&lt;h2 id="retos-t%C3%A9cnicos-y-salvaguardas"&gt;Retos técnicos y salvaguardas&lt;/h2&gt;
&lt;p&gt;Cuando tu equipo da el salto, espera tropezar con varios obstáculos culturales y técnicos:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;El cambio de mentalidad transaccional:&lt;/strong&gt; los desarrolladores acostumbrados a transacciones ACID sobre toda la base de datos deben aprender a diseñar para la consistencia eventual. Si un servicio de pagos tiene éxito pero el de inventario falla más adelante, ¿cómo se maneja el rollback? (Respuesta: el patrón Saga y los eventos compensatorios).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Depuración distribuida:&lt;/strong&gt; rastrear una llamada desde un frontend moderno en React, a través de un API Gateway, hacia un microservicio Java, por Kafka, a través de un flujo de ACE y finalmente hasta un programa RPG exige un trazado distribuido sólido (OpenTelemetry). Sin IDs de correlación, resolver problemas es una pesadilla.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Transición de habilidades:&lt;/strong&gt; respeta el conocimiento profundo del dominio de tus veteranos del AS/400 y de ACE. Entienden las reglas de negocio mejor que nadie. Júntalos con desarrolladores nativos de nube para que la lógica de negocio no se pierda en la traducción durante la reescritura.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="conclusi%C3%B3n"&gt;Conclusión&lt;/h2&gt;
&lt;p&gt;Migrar de AS/400 e IBM ACE a microservicios no es solo una mejora tecnológica; es un cambio fundamental en cómo tu organización construye, despliega y escala software.&lt;/p&gt;
&lt;p&gt;La meta no es borrar la historia ni fingir que los sistemas legacy nunca existieron. La meta es desacoplar la agilidad de tu negocio de una infraestructura que envejece, para que tu equipo itere rápido sobre capacidades nuevas mientras el núcleo confiable sigue haciendo lo que siempre ha hecho mejor, hasta su retiro final.&lt;/p&gt;


</description>
      <category>architecture</category>
      <category>cloud</category>
      <category>kubernetes</category>
      <category>microservices</category>
    </item>
    <item>
      <title>SaaS multi-tenant en Laravel: una base de datos, un global scope y las fugas que no detecta: 02 de 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Tue, 03 Nov 2026 13:00:06 +0000</pubDate>
      <link>https://dev.to/ifirestone/saas-multi-tenant-en-laravel-una-base-de-datos-un-global-scope-y-las-fugas-que-no-detecta-02-de-2nie</link>
      <guid>https://dev.to/ifirestone/saas-multi-tenant-en-laravel-una-base-de-datos-un-global-scope-y-las-fugas-que-no-detecta-02-de-2nie</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1563986768609-322da13575f3%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDJ8fHNhYXN8ZW58MHx8fHwxNzkyNzg2NjMwfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1563986768609-322da13575f3%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDJ8fHNhYXN8ZW58MHx8fHwxNzkyNzg2NjMwfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="SaaS multi-tenant en Laravel: una base de datos, un global scope y las fugas que no detecta: 02 de 08" width="2000" height="1333"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;blockquote&gt;Cómo aislar empresas dentro de una sola app Laravel: elegir un modelo de tenancy, resolver el tenant desde la URL, aplicarlo con un scope que falla cerrado y probar las fugas, incluidos los jobs y comandos que corren sin usuario.&lt;/blockquote&gt;
&lt;p&gt;Imagina un equipo que lanza un SaaS de facturación en tres meses. Cada consulta lleva un &lt;code&gt;where('company_id', $companyId)&lt;/code&gt;, los revisores lo buscan en cada pull request y durante medio año nada sale mal. Entonces alguien agrega un job nocturno que envía recordatorios de facturas vencidas. Lo ejecuta el scheduler, así que no hay usuario con sesión, y el helper que antes entregaba el id de la empresa devuelve null. La consulta pierde su filtro sin hacer ruido, y el job lee las facturas de todas las empresas.&lt;/p&gt;
&lt;p&gt;Nada de esa historia es exótico. Es lo que pasa cuando el aislamiento entre tenants depende de que cada desarrollador recuerde una línea, y de un contexto de petición que los jobs y los comandos no tienen.&lt;/p&gt;
&lt;p&gt;Este artículo trata de aislar empresas dentro de una sola app Laravel: qué modelo de tenancy elegir, cómo resolver la empresa actual, cómo imponerla para que olvidarla sea imposible y cómo probarlo. Cómo organizar la lógica de negocio (Actions, Data objects, Events) queda para los siguientes artículos de la serie.&lt;/p&gt;
&lt;h2 id="tres-formas-de-darle-a-cada-empresa-su-propio-espacio"&gt;Tres formas de darle a cada empresa su propio espacio&lt;/h2&gt;
&lt;p&gt;La primera decisión es dónde viven físicamente los datos de cada empresa. Hay tres respuestas habituales.&lt;/p&gt;


&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Modelo&lt;/th&gt;
&lt;th&gt;Qué separa a los tenants&lt;/th&gt;
&lt;th&gt;Qué cuesta&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Base de datos compartida, columna &lt;code&gt;company_id&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Tu código, opcionalmente respaldado por row-level security en la base de datos&lt;/td&gt;
&lt;td&gt;Lo más barato de operar: una migración, un pool de conexiones, un respaldo. El aislamiento es tan bueno como tu disciplina&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Un schema por empresa (PostgreSQL)&lt;/td&gt;
&lt;td&gt;El schema de la base de datos&lt;/td&gt;
&lt;td&gt;Una frontera real, pero cada migración corre una vez por schema y cada petición tiene que cambiar de schema&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Una base de datos por empresa&lt;/td&gt;
&lt;td&gt;El servidor de base de datos&lt;/td&gt;
&lt;td&gt;El aislamiento más fuerte y restauración por empresa, pero las migraciones, las conexiones y la factura crecen con cada cliente nuevo&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Para un producto que todavía busca su mercado, yo empezaría con la base de datos compartida. Se parece al argumento de &lt;a href="https://blog.ifirestone.dev/modular-monolith-or-microservices-a-framework-for-deciding-without-dogma/" rel="noopener noreferrer"&gt;Modular Monolith or Microservices: A Framework for Deciding Without Dogma&lt;/a&gt; (en inglés): la opción más barata suele dar la mayor parte del beneficio, siempre que dejes abierta la salida. El precio es que el aislamiento ahora vive en tu código. El resto de este artículo trata de hacer que ese código sea difícil de esquivar.&lt;/p&gt;
&lt;h2 id="la-url-decide-qui%C3%A9n-es-el-tenant"&gt;La URL decide quién es el tenant&lt;/h2&gt;
&lt;p&gt;La siguiente pregunta: ¿cómo dice una petición a qué empresa pertenece? Un subdominio, una cabecera, la sesión, un segmento de la ruta. La opción tentadora es una columna "empresa actual" en el usuario. Cambias una vez y todas las peticiones posteriores ya lo saben. Se rompe en cuanto alguien abre dos pestañas. La columna guarda una respuesta por usuario, las pestañas piden dos, y gana la última que cambió, para ambas.&lt;/p&gt;
&lt;p&gt;Yo prefiero la ruta: &lt;code&gt;/{company-slug}/invoices&lt;/code&gt;. La URL es el único estado que pertenece a la petición misma. Sobrevive a los marcadores y a los enlaces compartidos, y pone al tenant en tus logs.&lt;/p&gt;
&lt;p&gt;Un middleware resuelve el slug, comprueba la pertenencia y abre el contexto del tenant para el resto de la petición.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class ResolveCompany
{
    public function __construct(private TenantContext $tenant) {}

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request-&amp;gt;user() ?? throw new AuthenticationException;

        // Los bindings aún no se han ejecutado, así que esto sigue siendo el slug crudo.
        $company = Company::where('slug', $request-&amp;gt;route('company'))-&amp;gt;first();

        abort_if(
            $company === null || ! $user-&amp;gt;companies()-&amp;gt;whereKey($company-&amp;gt;id)-&amp;gt;exists(),
            404,
        );

        return $this-&amp;gt;tenant-&amp;gt;runAs($company-&amp;gt;id, fn () =&amp;gt; $next($request));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Devuelvo 404 a quien no es miembro para que la URL no confirme que una empresa existe. Un 403 es más amable con un usuario legítimo que se equivocó al escribir, así que elige uno a conciencia.&lt;/p&gt;
&lt;p&gt;Hay una trampa, y es de orden. El route model binding ocurre en &lt;code&gt;SubstituteBindings&lt;/code&gt;, y cuando se resuelve &lt;code&gt;{invoice}&lt;/code&gt;, esa consulta pasa por los global scopes del modelo. Si el tenant todavía no está definido, el binding corre sin scope. En la &lt;a href="https://laravel.com/docs/13.x/middleware" rel="noopener noreferrer"&gt;lista de prioridad de middleware&lt;/a&gt; por defecto de Laravel, ese middleware también está antes de la autenticación, y por eso el código de arriba lee el usuario por su cuenta. Mueve el middleware del tenant antes de los bindings en &lt;code&gt;bootstrap/app.php&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-&amp;gt;withMiddleware(function (Middleware $middleware): void {
    $middleware-&amp;gt;prependToPriorityList(
        before: \Illuminate\Routing\Middleware\SubstituteBindings::class,
        prepend: \App\Http\Middleware\ResolveCompany::class,
    );
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Y las rutas:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Route::middleware(['auth', ResolveCompany::class])
    -&amp;gt;prefix('{company}')
    -&amp;gt;group(function () {
        Route::resource('invoices', InvoiceController::class);
    });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;El middleware llama a algo llamado &lt;code&gt;TenantContext&lt;/code&gt;. Esa es la siguiente pieza, y la que necesitará el job nocturno.&lt;/p&gt;
&lt;h2 id="un-solo-lugar-que-sabe-cu%C3%A1l-es-la-empresa-actual"&gt;Un solo lugar que sabe cuál es la empresa actual&lt;/h2&gt;
&lt;p&gt;La solución a la historia del principio empieza con una regla: nadie lee el id de la empresa desde &lt;code&gt;auth()-&amp;gt;user()&lt;/code&gt;. Todo se lo pregunta a un objeto pequeño, y quien quiera ejecutar código como una empresa tiene que decirlo en voz alta.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;final class TenantContext
{
    private ?int $companyId = null;

    public function id(): ?int
    {
        return $this-&amp;gt;companyId;
    }

    public function runAs(int $companyId, Closure $callback): mixed
    {
        $previous = $this-&amp;gt;companyId;
        $this-&amp;gt;companyId = $companyId;

        try {
            return $callback();
        } finally {
            $this-&amp;gt;companyId = $previous;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Regístralo con &lt;code&gt;scoped&lt;/code&gt;, no con &lt;code&gt;singleton&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$this-&amp;gt;app-&amp;gt;scoped(TenantContext::class);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Según la &lt;a href="https://laravel.com/docs/13.x/container" rel="noopener noreferrer"&gt;documentación del container&lt;/a&gt;, las instancias scoped se descartan cuando un worker de Octane toma una petición nueva o un worker de colas toma un job nuevo. Un singleton normal arrastraría al tenant anterior a la siguiente unidad de trabajo, que es la misma fuga con otro disfraz. El bloque &lt;code&gt;finally&lt;/code&gt; es una segunda línea de defensa para el caso en que el código llame a &lt;code&gt;runAs&lt;/code&gt; y lance una excepción.&lt;/p&gt;
&lt;h2 id="un-scope-que-falla-cerrado"&gt;Un scope que falla cerrado&lt;/h2&gt;
&lt;p&gt;Ahora la parte que todos escriben primero. Un &lt;a href="https://laravel.com/docs/13.x/eloquent" rel="noopener noreferrer"&gt;global scope&lt;/a&gt; filtra todas las consultas de un modelo, y un trait puede engancharlo y rellenar &lt;code&gt;company_id&lt;/code&gt; al crear. La diferencia con la versión habitual está en qué pasa cuando no hay empresa: lanza una excepción en lugar de omitir el filtro (&lt;em&gt;fail closed&lt;/em&gt;).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class TenantScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $companyId = app(TenantContext::class)-&amp;gt;id()
            ?? throw new MissingTenantContext($model::class);

        $builder-&amp;gt;where($model-&amp;gt;qualifyColumn('company_id'), $companyId);
    }
}

trait BelongsToCompany
{
    public static function bootBelongsToCompany(): void
    {
        static::addGlobalScope(new TenantScope);

        static::creating(function (Model $model): void {
            $model-&amp;gt;company_id ??= app(TenantContext::class)-&amp;gt;id()
                ?? throw new MissingTenantContext($model::class);
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Acóplalo a una migración donde la columna no pueda ser nula y la empresa vaya primero en los índices, ya que casi todas las consultas filtran por ella:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$table-&amp;gt;foreignId('company_id')-&amp;gt;constrained();
$table-&amp;gt;string('number');
$table-&amp;gt;unique(['company_id', 'number']);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;El costo de fallar cerrado es real. Las pantallas de administración, los seeders, los reportes entre todas las empresas y cualquier otra cosa que legítimamente necesite datos sin scope tienen que decirlo con &lt;code&gt;Invoice::withoutGlobalScope(TenantScope::class)&lt;/code&gt;. Yo lo cuento como una ventaja. Cada consulta sin scope es ahora una línea que puedes buscar con grep en la revisión de código, y la lista debería mantenerse corta.&lt;/p&gt;
&lt;p&gt;Un scope también tiene puntos ciegos, y conviene conocerlos antes de confiar en él:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;DB::table('invoices')&lt;/code&gt; y el SQL crudo nunca ven los scopes de Eloquent.&lt;/li&gt;
&lt;li&gt;Las reglas de validación &lt;code&gt;unique&lt;/code&gt; y &lt;code&gt;exists&lt;/code&gt; consultan la tabla directamente, así que ignoran el scope. Agrega la condición tú mismo: &lt;code&gt;Rule::unique('invoices', 'number')-&amp;gt;where('company_id', $companyId)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Cualquier cosa que cruce un modelo que no use el trait es tan segura como ese otro modelo.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="el-job-nocturno-otra-vez"&gt;El job nocturno, otra vez&lt;/h2&gt;
&lt;p&gt;Volvamos al job de recordatorios. Con las reglas nuevas no puede correr como estaba escrito, porque nada define la empresa. Así que el job recibe la empresa de forma explícita y un middleware de job abre el contexto a su alrededor. El middleware de jobs, descrito en la &lt;a href="https://laravel.com/docs/13.x/queues" rel="noopener noreferrer"&gt;documentación de colas&lt;/a&gt;, envuelve al job igual que el middleware de rutas envuelve una petición.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class RunsAsCompany
{
    public function handle(object $job, Closure $next): void
    {
        app(TenantContext::class)-&amp;gt;runAs($job-&amp;gt;companyId, fn () =&amp;gt; $next($job));
    }
}

class SendOverdueReminders implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $companyId) {}

    public function middleware(): array
    {
        return [new RunsAsCompany];
    }

    public function handle(): void
    {
        // Invoice::query() ahora está filtrada a $this-&amp;gt;companyId
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;El scheduler reparte un job por empresa:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Schedule::call(function () {
    Company::query()-&amp;gt;each(
        fn (Company $company) =&amp;gt; SendOverdueReminders::dispatch($company-&amp;gt;id)
    );
})-&amp;gt;dailyAt('02:00');
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tiene un costo: N jobs en lugar de uno. A cambio, una empresa lenta o que falla no bloquea a las demás, los reintentos se quedan dentro de un solo tenant y el tenant es visible en el payload en lugar de esconderse en estado ambiental. &lt;code&gt;Company&lt;/code&gt; en sí no usa el trait, porque es el tenant.&lt;/p&gt;
&lt;h2 id="empresas-usuarios-y-roles"&gt;Empresas, usuarios y roles&lt;/h2&gt;
&lt;p&gt;En un producto multiempresa, una persona suele pertenecer a varias empresas. Eso decide dónde vive el rol. Pertenece a la membresía, una tabla pivote &lt;code&gt;company_user&lt;/code&gt; con una columna &lt;code&gt;role&lt;/code&gt;, y no al usuario. La misma persona puede ser admin en una empresa y viewer en otra, y el middleware ya sabe de qué empresa trata la petición.&lt;/p&gt;
&lt;p&gt;La tentación es darle un rango a los roles y comparar números. Funciona durante un tiempo. Los permisos como cadenas simples por rol (&lt;code&gt;invoice:create&lt;/code&gt;, &lt;code&gt;invoice:void&lt;/code&gt;) envejecen mejor, porque el día que alguien pida un rol que pueda anular facturas pero no editarlas, agregas una fila en lugar de reordenar una jerarquía. Comprueba los permisos con las policies de Laravel, y pasa el rol de la membresía, no una marca a nivel de usuario.&lt;/p&gt;
&lt;h2 id="demu%C3%A9stralo-con-un-test-que-intenta-filtrar"&gt;Demuéstralo con un test que intenta filtrar&lt;/h2&gt;
&lt;p&gt;Un scope que no has atacado es un scope que esperas que funcione. Tres tests cubren la historia hasta aquí, escritos con Pest:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;it('nunca devuelve facturas de otra empresa', function () {
    $acme = Company::factory()-&amp;gt;create();
    $globex = Company::factory()-&amp;gt;create();
    $tenant = app(TenantContext::class);

    $tenant-&amp;gt;runAs($globex-&amp;gt;id, fn () =&amp;gt; Invoice::factory()-&amp;gt;create());

    expect($tenant-&amp;gt;runAs($acme-&amp;gt;id, fn () =&amp;gt; Invoice::count()))-&amp;gt;toBe(0);
});

it('se niega a consultar sin tenant', function () {
    Invoice::count();
})-&amp;gt;throws(MissingTenantContext::class);

it('devuelve 404 para una empresa a la que el usuario no pertenece', function () {
    $other = Company::factory()-&amp;gt;create();

    $this-&amp;gt;actingAs(User::factory()-&amp;gt;create())
        -&amp;gt;get("/{$other-&amp;gt;slug}/invoices")
        -&amp;gt;assertNotFound();
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;El segundo test es el que habría atrapado la historia del principio. Cuando estos tests existan, agrega una guarda que liste todas las tablas con una columna &lt;code&gt;company_id&lt;/code&gt; y falle si su modelo no usa el trait. Las tablas nuevas son donde nacen las fugas.&lt;/p&gt;
&lt;h2 id="d%C3%B3nde-deja-de-funcionar-el-schema-compartido"&gt;Dónde deja de funcionar el schema compartido&lt;/h2&gt;
&lt;p&gt;Este diseño tiene límites, y es mejor verlos pronto. Un solo tenant grande puede dominar los índices y el pool de conexiones, así que los vecinos ruidosos son una posibilidad real. Restaurar una empresa desde un respaldo significa extraer sus filas de un respaldo de todos. Y algunos clientes, sobre todo los enterprise o regulados, pedirán su propia base de datos por muy bueno que sea tu scope.&lt;/p&gt;
&lt;p&gt;El diseño también te deja una salida. Como todas las consultas pasan por un solo contexto y un solo trait, mover a un cliente grande a su propia base de datos más adelante es un refactor mucho más pequeño que en un código lleno de cláusulas &lt;code&gt;where&lt;/code&gt; escritas a mano. Ese es el argumento para hacerlo así aunque nunca necesites la salida.&lt;/p&gt;
&lt;h2 id="conclusi%C3%B3n"&gt;Conclusión&lt;/h2&gt;
&lt;p&gt;El job nocturno que envió correos a los clientes equivocados no necesitaba un filtro más ingenioso. Necesitaba un sistema donde correr sin empresa sea un error, y donde ese error aparezca en un test mucho antes de que lo vea un cliente. Resuelve el tenant desde la URL, guárdalo en un solo lugar, haz que el scope falle cerrado e intenta filtrar a propósito.&lt;/p&gt;
&lt;p&gt;Si quieres una acción para hoy, busca con grep en tu código &lt;code&gt;auth()-&amp;gt;user()-&amp;gt;company_id&lt;/code&gt; y &lt;code&gt;withoutGlobalScopes&lt;/code&gt;, y escribe el test "se niega a consultar sin tenant". En el siguiente artículo dejamos atrás el aislamiento y vemos dónde debe vivir la lógica de negocio para que los controladores se mantengan delgados.&lt;/p&gt;

</description>
      <category>backend</category>
      <category>database</category>
      <category>laravel</category>
      <category>saas</category>
    </item>
    <item>
      <title>Building a Multi-Tenant SaaS in Laravel: The Series I Wish I Had Read First: 01 of 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Tue, 03 Nov 2026 01:00:07 +0000</pubDate>
      <link>https://dev.to/ifirestone/building-a-multi-tenant-saas-in-laravel-the-series-i-wish-i-had-read-first-01-of-08-die</link>
      <guid>https://dev.to/ifirestone/building-a-multi-tenant-saas-in-laravel-the-series-i-wish-i-had-read-first-01-of-08-die</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1556155092-490a1ba16284%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDF8fHNhYXN8ZW58MHx8fHwxNzkyNzkxMTIxfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1556155092-490a1ba16284%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDF8fHNhYXN8ZW58MHx8fHwxNzkyNzkxMTIxfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Building a Multi-Tenant SaaS in Laravel: The Series I Wish I Had Read First: 01 of 08" width="2000" height="1333"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is the article I would have wanted to read before I started building a multi-tenant system. It would have saved me time, a lot of rewritten code, and many hours migrating systems that were already running.&lt;/p&gt;
&lt;p&gt;Most of the expensive decisions in a multi-tenant SaaS are cheap on day one and costly on day four hundred. Where the tenant lives in the schema, how a request finds its company, what a background job knows about who it works for: you can get each of them right in an afternoon at the start, or fix them later with a migration, a rewrite and a nervous deploy. I know the second path because I have walked it. This series is what I would do on the first day if I started again, knowing what I know now.&lt;/p&gt;
&lt;p&gt;Here is one of those paths. I started multi-tenant, but not multi-user. Adding multi-user later wasn't a feature. It was a rewrite that touched the whole system. And the guards that kept one tenant's data away from another weren't built as well as they should have been. Both problems sit at the foundation, which is why the first article of the series deals with who belongs to which company and how a request finds out.&lt;/p&gt;
&lt;h2 id="what-this-series-is"&gt;What This Series Is&lt;/h2&gt;
&lt;p&gt;It is a set of decisions with reasons attached, written for developers who already build with Laravel and want to design and deliver a multi-tenant SaaS without learning the hard parts the slow way. Every article follows the same fictional product, an invoicing app where the tenant is a &lt;code&gt;Company&lt;/code&gt;, so the examples connect from one article to the next.&lt;/p&gt;
&lt;p&gt;It is not a package guide, and it is not a framework. You won't find a library to install that solves tenancy for you. You will find the pieces I think are worth building yourself, why, and what each one costs. Where a decision is a judgment call, I say so.&lt;/p&gt;
&lt;h2 id="what-it-assumes"&gt;What It Assumes&lt;/h2&gt;
&lt;p&gt;A few choices are fixed so the series can go deep instead of wide:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;One Laravel application and one database&lt;/strong&gt;, with a &lt;code&gt;company_id&lt;/code&gt; column on tenant-owned tables. If you are still deciding between a modular monolith and microservices, that is a different question, and I wrote about how to approach it in &lt;a href="https://dev.to/ifirestone/modular-monolith-or-microservices-a-framework-for-deciding-without-dogma-4ppa"&gt;Modular Monolith or Microservices: A Framework for Deciding Without Dogma&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Laravel 13 and PostgreSQL&lt;/strong&gt; in the examples, although most of it applies to other versions and to MySQL. The one article that depends on PostgreSQL says so up front.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A reader with some experience.&lt;/strong&gt; I don't explain what a middleware or a queue is.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;What it leaves out on purpose: a separate database per tenant, single sign-on, and the details of any specific payment provider. Each is worth its own series, and none of them is where a first version usually hurts.&lt;/p&gt;
&lt;h2 id="what-youll-find"&gt;What You'll Find&lt;/h2&gt;
&lt;p&gt;These are the articles in the order I would read them. Each one stands on its own once you know the tenant context from the first. I update this list as the series is published: a title with a link is already out, and a title without one is still to come.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Multi-Tenant SaaS in Laravel: One Database, a Global Scope, and the Leaks It Doesn't Catch.&lt;/strong&gt; The foundation: how a request finds its company, a scope that fails closed, and what the scope still misses.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Killing Fat Controllers in Laravel: Actions as the Home for Business Logic.&lt;/strong&gt; Where the rules live, so a controller, a command and an API share one implementation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Objects, Concerns and Events: The Supporting Cast of a Laravel Action.&lt;/strong&gt; What feeds an Action, what it shares and what it announces, with the tenant context carried into queued listeners.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;From Idea to First Paying Customer: A Delivery Roadmap for a Multi-Tenant Laravel SaaS.&lt;/strong&gt; The order of work: walls before rooms, one slice early, plan limits, billing webhooks and safe deploys.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Testing Tenant Isolation in Laravel: Leak Tests, Guard Tests and What They Still Miss.&lt;/strong&gt; How to prove, on every commit, that one company can't see another.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Observability Per Tenant in Laravel: Logs, Metrics and Errors by Company.&lt;/strong&gt; How to answer "what happened to this company?" without drowning in data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Row-Level Security in PostgreSQL: A Second Wall for a Multi-Tenant Laravel App.&lt;/strong&gt; An optional database-level layer behind the application scope, and the cases where it is worth its cost.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="how-to-read-it"&gt;How to Read It&lt;/h2&gt;
&lt;p&gt;Two habits will help. First, treat the code as a starting point. The snippets are small on purpose, and I haven't run them against your schema, your policies or your deploy setup. Second, pay attention to the cost sections. Every pattern here has a price, and the honest question is not "is this good practice?" but "is it worth it for my team, at my size, this year?"&lt;/p&gt;
&lt;p&gt;Sometimes the answer is no. A pass-through Action, a Data object for two arguments or a database policy for a prototype are all ways to spend effort you needed elsewhere.&lt;/p&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;I'm writing this series because the most useful advice I can give my past self is also the advice most teams hear too late: decide the foundations early, make them testable, and keep the rest boring. If you are about to start a multi-tenant product, or you are early enough that the foundations can still change, begin with the tenant context. Everything else in the series is built on it.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>backend</category>
      <category>laravel</category>
      <category>saas</category>
    </item>
    <item>
      <title>Migrar de un sistema legacy a microservicios sin documentación ni control total</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Sat, 31 Oct 2026 13:00:07 +0000</pubDate>
      <link>https://dev.to/ifirestone/migrar-de-un-sistema-legacy-a-microservicios-sin-documentacion-ni-control-total-346o</link>
      <guid>https://dev.to/ifirestone/migrar-de-un-sistema-legacy-a-microservicios-sin-documentacion-ni-control-total-346o</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1674027001834-719c347d1eca%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDE1M3x8bWlncmF0ZSUyMHNvZnR3YXJlfGVufDB8fHx8MTc5MjgwOTE3NHww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1674027001834-719c347d1eca%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDE1M3x8bWlncmF0ZSUyMHNvZnR3YXJlfGVufDB8fHx8MTc5MjgwOTE3NHww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Migrar de un sistema legacy a microservicios sin documentación ni control total" width="2000" height="1125"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;blockquote&gt;Cómo reemplazar un sistema legacy que no puedes leer del todo, cambiar ni apagar: aprende primero su comportamiento real, rodéalo con una fachada strangler y demuestra que los nuevos servicios igualan a los viejos antes de hacer el corte.&lt;/blockquote&gt;
&lt;p&gt;Imagina una empresa cuya tienda en línea lleva doce años funcionando sobre una sola aplicación. Los autores originales se fueron hace mucho. El wiki describe una versión del sistema que ya no existe. Un módulo lo escribió un proveedor y llega como una librería compilada de la que nadie tiene el código fuente. Y aun así la tienda procesa pedidos todos los días, y el negocio repite lo mismo que dijo el año pasado: "funciona, no lo rompas".&lt;/p&gt;
&lt;p&gt;Entonces alguien escribe "migrar a microservicios" en el roadmap.&lt;/p&gt;
&lt;p&gt;Este artículo sigue a esa tienda hipotética por las partes de una migración que los diagramas habituales se saltan: no saber qué hace realmente el sistema, no tener permiso para cambiarlo y tener que superar algo que lleva años probado en batalla. Si todavía estás decidiendo si los microservicios son el destino correcto, empieza por &lt;a href="https://blog.ifirestone.dev/arquitectura-de-microservicios/" rel="noreferrer noopener"&gt;Arquitectura Microservicios&lt;/a&gt;  y &lt;a href="https://blog.ifirestone.dev/monolito-modular-o-microservicios-un-marco-para-decidir-sin-dogmas/" rel="noreferrer noopener"&gt;Monolito modular o microservicios: un marco para decidir sin dogmas&lt;/a&gt;. Aquí damos la decisión por tomada y preguntamos cómo sobrevivirla.&lt;/p&gt;
&lt;h2 id="la-reescritura-que-parec%C3%ADa-un-plan"&gt;La reescritura que parecía un plan&lt;/h2&gt;
&lt;p&gt;El primer instinto es empezar de cero: construir el sistema nuevo al lado del viejo y cambiar cuando esté listo. Tienta porque promete dejar atrás el desorden.&lt;/p&gt;
&lt;p&gt;Falla por una razón que no tiene nada que ver con la calidad del código. Mientras se construye el sistema nuevo, el viejo sigue cambiando: correcciones de errores, reglas de precios, un ajuste regulatorio. El objetivo se mueve. El equipo termina manteniendo dos sistemas sin terminar ninguno, y el cambio se convierte en un solo evento grande e irreversible que no se pudo probar con tráfico real.&lt;/p&gt;
&lt;p&gt;La alternativa tiene nombre: la &lt;strong&gt;higuera estranguladora&lt;/strong&gt; (&lt;em&gt;strangler fig&lt;/em&gt;), descrita por Martin Fowler en &lt;a href="https://martinfowler.com/bliki/StranglerFigApplication.html" rel="noopener noreferrer"&gt;Strangler Fig &lt;/a&gt; y documentada en el &lt;a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/strangler-fig" rel="noopener noreferrer"&gt;Azure Architecture Center&lt;/a&gt;. Como la enredadera que crece alrededor de un árbol, el sistema nuevo envuelve al viejo y lo reemplaza pieza por pieza, mientras el viejo sigue atendiendo a los usuarios. Cada paso es pequeño y reversible. Esa propiedad es la que hace posible todo lo demás en este artículo.&lt;/p&gt;
&lt;p&gt;Pero un strangler necesita saber dónde cortar. Y para eso, la tienda primero tiene que responder una pregunta incómoda.&lt;/p&gt;
&lt;h2 id="%C2%BFqu%C3%A9-hace-realmente-el-sistema-viejo"&gt;¿Qué hace realmente el sistema viejo?&lt;/h2&gt;
&lt;p&gt;Sin documentación confiable, la fuente de verdad es el sistema en ejecución. El código te dice lo que puede hacer; producción te dice lo que hace. No son la misma lista.&lt;/p&gt;
&lt;p&gt;El equipo empieza escuchando, más o menos en este orden:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Capturar tráfico real.&lt;/strong&gt; Los logs de acceso, los del API gateway o un proxy delante de la aplicación legacy muestran qué endpoints se llaman, con qué frecuencia y con qué payloads. Los endpoints que nadie llama desde hace un año son candidatos a eliminarse, no a migrarse.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Leer la base de datos como un contrato.&lt;/strong&gt; Las tablas, las llaves foráneas, los triggers y los procedimientos almacenados suelen guardar reglas de negocio que nunca llegaron al código de la aplicación. Un trigger que descuenta stock cuando se inserta un pedido es una funcionalidad, aunque ningún desarrollador recuerde haberlo escrito.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Listar los consumidores ocultos.&lt;/strong&gt; Jobs nocturnos, hojas de cálculo que consultan la base de datos directamente, un socio que llama a un endpoint no documentado. Son los clientes que se rompen en silencio.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Escribir pruebas de caracterización.&lt;/strong&gt; Michael Feathers llama &lt;em&gt;characterization tests&lt;/em&gt; (en &lt;em&gt;Working Effectively with Legacy Code&lt;/em&gt;) a las pruebas que registran lo que el código hace hoy, bien o mal. Envías entradas conocidas, guardas las salidas, y desde entonces cualquier cambio de comportamiento se hace visible.&lt;/li&gt;
&lt;/ol&gt;
&lt;blockquote&gt;Las pruebas de caracterización no dicen que el comportamiento legacy sea correcto. Dicen que es el comportamiento del que dependen hoy tus clientes. Si una rareza es un error o una funcionalidad es una decisión de negocio, y es mucho más barato tomarla antes de la migración que después.&lt;/blockquote&gt;
&lt;p&gt;Al final de esta fase la tienda tiene algo que nunca tuvo: una descripción escrita y ejecutable de su propio sistema. Solo ahora puede elegir qué extraer primero.&lt;/p&gt;
&lt;h2 id="cortar-donde-no-puedes-editar"&gt;Cortar donde no puedes editar&lt;/h2&gt;
&lt;p&gt;Aquí aparece el segundo problema. Supón que la tienda quiere mover los pagos a su propio servicio. El paso obvio es cambiar el código legacy para que llame al servicio nuevo en lugar de a su módulo interno de pagos. Pero el equipo no puede: el módulo es un binario del proveedor, o el proceso de release de la aplicación legacy tarda meses, o nadie se atreve a tocar el archivo.&lt;/p&gt;
&lt;p&gt;Cuando no puedes cambiar el interior, trabajas por fuera. Hay tres costuras que no requieren editar el código legacy:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;El borde.&lt;/strong&gt; Pon una fachada, como un reverse proxy o un API gateway, delante de la aplicación legacy. Al principio reenvía todo. Luego, ruta por ruta, envía peticiones específicas al servicio nuevo. Los usuarios ven las mismas URLs; la fachada decide quién responde.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Los datos.&lt;/strong&gt; Si el servicio nuevo necesita datos que son de la base de datos legacy, no la consultes directamente desde el servicio nuevo. Captura los cambios con &lt;em&gt;change data capture&lt;/em&gt; o una exportación estilo outbox y aliméntalos al servicio nuevo, para que el esquema legacy siga siendo un detalle de implementación.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;La capa de traducción.&lt;/strong&gt; El sistema legacy habla su propio dialecto: códigos de estado raros, un registro de cliente con cuarenta columnas, fechas guardadas como texto. Una &lt;strong&gt;capa anticorrupción&lt;/strong&gt; (&lt;em&gt;anti-corruption layer&lt;/em&gt;, un término de Domain-Driven Design) traduce entre ese dialecto y el modelo limpio del servicio nuevo. Sin ella, el diseño legacy se filtra a cada servicio nuevo y acabas reconstruyendo el sistema viejo en piezas más pequeñas.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;# Reglas ilustrativas de gateway: la fachada es dueña de la decisión de enrutamiento&lt;br&gt;
routes:

&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;code&gt;&lt;br&gt;
&lt;li&gt;path: /api/payments/**
target: payments-service   # nuevo&lt;/li&gt;
&lt;br&gt;
&lt;/code&gt;&lt;li&gt;&lt;code&gt;path: /**&lt;br&gt;
target: legacy-app         # todo lo demás, sin cambios&lt;br&gt;
&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;La fachada también le da a la tienda su red de seguridad. Si el servicio nuevo de pagos se comporta mal, volver atrás es un cambio de enrutamiento, no un despliegue.&lt;/p&gt;
&lt;p&gt;El primer servicio ya corre detrás de la fachada. La siguiente pregunta es la que le importa al negocio: ¿es tan bueno como lo que reemplazó?&lt;/p&gt;
&lt;h2 id="superar-a-un-sistema-con-doce-a%C3%B1os-de-pruebas"&gt;Superar a un sistema con doce años de pruebas&lt;/h2&gt;
&lt;p&gt;Los sistemas legacy tienen una ventaja fácil de subestimar: los ha golpeado cada pedido extraño, cada tormenta de reintentos, cada reporte de fin de mes. El servicio nuevo, en comparación, no ha sido probado en el mundo real. "Código más limpio" no es un argumento que sobreviva al primer incidente.&lt;/p&gt;
&lt;p&gt;Por eso la tienda trata la paridad como un requisito con evidencia, en cuatro pasos:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Medir primero la línea base del legacy.&lt;/strong&gt; Percentiles de latencia, tasa de errores, throughput en el pico y el costo de operarlo. No puedes afirmar que igualas algo que nunca mediste, y un monolito viejo en una red local suele ser más rápido por petición que un sistema distribuido con saltos de red.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Definir "al menos igual de bueno" por capacidad.&lt;/strong&gt; En pagos importan más la corrección y la idempotencia que la velocidad pura. En la búsqueda de productos importa más la latencia. Escríbelo como objetivos de nivel de servicio (SLO) antes de construir.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Correr en modo sombra.&lt;/strong&gt; La fachada envía cada petición real al sistema legacy, que responde al usuario, y una copia al servicio nuevo, cuya respuesta solo se registra. Compara las dos respuestas. Las diferencias son errores del servicio nuevo o comportamiento no documentado del viejo, y ambos conviene encontrarlos antes de que afecten a un cliente.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mover el tráfico gradualmente.&lt;/strong&gt; Usa feature flags o enrutamiento ponderado: una parte pequeña del tráfico, luego más, vigilando los SLO en cada paso. El camino legacy se mantiene vivo hasta que el nuevo haya aguantado un ciclo de negocio completo, incluidos los momentos incómodos como el cierre de mes.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;El modo sombra tiene costos que conviene decir. Las peticiones duplicadas no deben duplicar efectos secundarios, así que una llamada de pago en sombra necesita un modo "dry run" o un sandbox. Y necesitas observabilidad real en ambos lados antes de que nada de esto funcione: trazas, métricas y logs que puedas correlacionar.&lt;/p&gt;
&lt;h2 id="lo-que-esto-te-cuesta"&gt;Lo que esto te cuesta&lt;/h2&gt;
&lt;p&gt;Una migración así es más lenta e incómoda que una reescritura en el papel. Sé honesto con la factura:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Dos sistemas a la vez.&lt;/strong&gt; Durante un buen tiempo operas, parchas y aseguras ambos. El sistema legacy no se abarata mientras lo reemplazas.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Una fachada de apariencia permanente.&lt;/strong&gt; El gateway y la capa anticorrupción son componentes extra que hay que operar. Algunos sobrevivirán a la migración.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;La complejidad de los sistemas distribuidos&lt;/strong&gt; llega con el primer servicio, como se describe en &lt;a href="https://blog.ifirestone.dev/arquitectura-de-microservicios/" rel="noreferrer noopener"&gt;Arquitectura Microservicios&lt;/a&gt; : fallos de red, versionado, monitoreo entre servicios.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No todo debe moverse.&lt;/strong&gt; Algunos módulos son estables, cambian poco y no tienen problemas de escala. Dejarlos en el núcleo legacy, detrás de la fachada, puede ser el estado final correcto.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Depende del sistema, pero un resultado común es un núcleo legacy más pequeño que se queda, rodeado de un puñado de servicios que se ganaron su independencia.&lt;/p&gt;
&lt;h2 id="conclusi%C3%B3n"&gt;Conclusión&lt;/h2&gt;
&lt;p&gt;La tienda del principio creía que su problema era la tecnología vieja. Los problemas más difíciles resultaron ser el conocimiento que faltaba, el acceso restringido y una vara de prueba muy alta. Cada uno tiene una respuesta práctica: aprender el comportamiento real desde producción, trabajar por el borde, los datos y una capa de traducción en lugar de editar lo intocable, y tratar la paridad con el sistema legacy como algo que se mide, no que se supone.&lt;/p&gt;
&lt;p&gt;Si enfrentas una migración así, un primer paso concreto es pequeño: pon un proxy delante de la aplicación legacy, reenvía todo y empieza a leer los logs. En una semana aprenderás más sobre tu sistema que lo que el wiki te ha dicho en años.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>microservices</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>Construir un SaaS multi-tenant en Laravel: la serie que me habría gustado leer primero: 01 de 08</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Fri, 30 Oct 2026 13:00:07 +0000</pubDate>
      <link>https://dev.to/ifirestone/construir-un-saas-multi-tenant-en-laravel-la-serie-que-me-habria-gustado-leer-primero-01-de-08-1k1f</link>
      <guid>https://dev.to/ifirestone/construir-un-saas-multi-tenant-en-laravel-la-serie-que-me-habria-gustado-leer-primero-01-de-08-1k1f</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1559526324-593bc073d938%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDEzfHxzYWFzfGVufDB8fHx8MTc5Mjc4NjYzMHww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1559526324-593bc073d938%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDEzfHxzYWFzfGVufDB8fHx8MTc5Mjc4NjYzMHww%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Construir un SaaS multi-tenant en Laravel: la serie que me habría gustado leer primero: 01 de 08" width="2000" height="1333"&gt;&lt;/a&gt;&lt;/p&gt;


&lt;blockquote&gt;Por qué escribo una serie sobre diseñar y entregar un SaaS multi-tenant en Laravel: qué haría distinto desde el primer día, qué cubre la serie, a quién va dirigida y cómo leerla.&lt;/blockquote&gt;
&lt;p&gt;Este es el artículo que habría querido leer antes de empezar a construir un sistema multi-tenant. Me habría ahorrado tiempo, mucho código reescrito y muchas horas migrando sistemas que ya estaban en marcha.&lt;/p&gt;
&lt;p&gt;La mayoría de las decisiones caras en un SaaS multi-tenant son baratas el día uno y costosas el día cuatrocientos. Dónde vive el tenant en el schema, cómo una petición encuentra su empresa, qué sabe un job en segundo plano sobre para quién trabaja: cada una se puede resolver bien en una tarde al principio, o arreglar después con una migración, una reescritura y un deploy con los nervios de punta. Conozco el segundo camino porque lo he recorrido. Esta serie es lo que haría el primer día si empezara de nuevo, sabiendo lo que sé ahora.&lt;/p&gt;
&lt;p&gt;Aquí va uno de esos caminos. Empecé multi-tenant, pero no multiusuario. Añadir el multiusuario después no fue una funcionalidad. Fue una reescritura que tocó todo el sistema. Y las guardas que mantienen los datos de un tenant lejos de otro no estaban tan bien construidas como debían. Los dos problemas están en los cimientos, y por eso el primer artículo de la serie trata de quién pertenece a qué empresa y cómo lo descubre una petición.&lt;/p&gt;
&lt;h2 id="qu%C3%A9-es-esta-serie"&gt;Qué es esta serie&lt;/h2&gt;
&lt;p&gt;Es un conjunto de decisiones con sus razones adjuntas, escrito para desarrolladores que ya construyen con Laravel y quieren diseñar y entregar un SaaS multi-tenant sin aprender las partes difíciles por el camino lento. Cada artículo sigue el mismo producto ficticio, una app de facturación donde el tenant es una &lt;code&gt;Company&lt;/code&gt;, de modo que los ejemplos conectan de uno a otro.&lt;/p&gt;
&lt;p&gt;No es una guía de paquetes, y no es un framework. No encontrarás una librería que instalar que te resuelva el tenancy. Encontrarás las piezas que creo que vale la pena construir tú mismo, por qué, y qué cuesta cada una. Donde una decisión es cuestión de criterio, lo digo.&lt;/p&gt;
&lt;h2 id="qu%C3%A9-asume"&gt;Qué asume&lt;/h2&gt;
&lt;p&gt;Unas pocas elecciones están fijadas para que la serie pueda ir en profundidad y no en extensión:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Una aplicación Laravel y una base de datos&lt;/strong&gt;, con una columna &lt;code&gt;company_id&lt;/code&gt; en las tablas que pertenecen a un tenant. Si todavía decides entre un monolito modular y microservicios, esa es otra pregunta, y escribí sobre cómo abordarla en &lt;a href="https://blog.ifirestone.dev/monolito-modular-o-microservicios-un-marco-para-decidir-sin-dogmas/" rel="noreferrer noopener"&gt;Monolito modular o microservicios: un marco para decidir sin dogmas.&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Laravel 13 y PostgreSQL&lt;/strong&gt; en los ejemplos, aunque casi todo aplica a otras versiones y a MySQL. El único artículo que depende de PostgreSQL lo dice desde el principio.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Un lector con algo de experiencia.&lt;/strong&gt; No explico qué es un middleware ni una cola.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Lo que se deja fuera a propósito: una base de datos separada por tenant, el single sign-on y los detalles de cualquier proveedor de pagos concreto. Cada uno merece su propia serie, y ninguno es donde suele doler una primera versión.&lt;/p&gt;
&lt;h2 id="qu%C3%A9-encontrar%C3%A1s"&gt;Qué encontrarás&lt;/h2&gt;
&lt;p&gt;Estos son los artículos en el orden en que yo los leería. Cada uno se sostiene solo una vez que conoces el contexto del tenant del primero. Actualizo esta lista a medida que se publica la serie: un título con enlace ya está publicado, y un título sin enlace está por llegar.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;SaaS multi-tenant en Laravel: una base de datos, un global scope y las fugas que no detecta.&lt;/strong&gt; El cimiento: cómo una petición encuentra su empresa, un scope que falla cerrado y lo que el scope todavía no ve.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Adiós a los controladores gordos en Laravel: las Actions como hogar de la lógica de negocio.&lt;/strong&gt; Dónde viven las reglas, para que un controlador, un comando y una API compartan una sola implementación.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data objects, Concerns y Events: el reparto de apoyo de una Action en Laravel.&lt;/strong&gt; Qué alimenta a una Action, qué comparte y qué anuncia, con el contexto de tenant llevado a los listeners en cola.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;De la idea al primer cliente de pago: una hoja de ruta de entrega para un SaaS multi-tenant en Laravel.&lt;/strong&gt; El orden del trabajo: muros antes que habitaciones, un slice temprano, límites de plan, webhooks de facturación y deploys seguros.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Probar el aislamiento entre tenants en Laravel: tests de fuga, tests de guarda y lo que aún no detectan.&lt;/strong&gt; Cómo demostrar, en cada commit, que una empresa no puede ver a otra.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Observabilidad por tenant en Laravel: logs, métricas y errores por empresa.&lt;/strong&gt; Cómo responder "¿qué le pasó a esta empresa?" sin ahogarte en datos.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Row-Level Security en PostgreSQL: un segundo muro para una app Laravel multi-tenant.&lt;/strong&gt; Una capa opcional a nivel de base de datos detrás del scope de la aplicación, y los casos en que vale su costo.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 id="c%C3%B3mo-leerla"&gt;Cómo leerla&lt;/h2&gt;
&lt;p&gt;Dos hábitos ayudarán. Primero, trata el código como un punto de partida. Los fragmentos son pequeños a propósito, y no los he ejecutado contra tu schema, tus policies ni tu configuración de deploy. Segundo, presta atención a las secciones de costos. Cada patrón de aquí tiene un precio, y la pregunta honesta no es "¿es esto una buena práctica?" sino "¿vale la pena para mi equipo, a mi tamaño, este año?".&lt;/p&gt;
&lt;p&gt;A veces la respuesta es que no. Una Action de paso, un Data object para dos argumentos o una política de base de datos para un prototipo son formas de gastar un esfuerzo que necesitabas en otro sitio.&lt;/p&gt;
&lt;h2 id="conclusi%C3%B3n"&gt;Conclusión&lt;/h2&gt;
&lt;p&gt;Escribo esta serie porque el consejo más útil que puedo darle a mi yo del pasado es también el que la mayoría de los equipos oye demasiado tarde: decide los cimientos pronto, hazlos comprobables y mantén aburrido todo lo demás. Si estás a punto de empezar un producto multi-tenant, o estás lo bastante al principio como para que los cimientos aún puedan cambiar, empieza por el contexto del tenant. Todo lo demás de la serie se apoya en él.&lt;/p&gt;


</description>
      <category>laravel</category>
      <category>architecture</category>
      <category>saas</category>
      <category>backend</category>
    </item>
    <item>
      <title>Arquitectura de microservicios</title>
      <dc:creator>Ivan Firestone</dc:creator>
      <pubDate>Wed, 28 Oct 2026 13:00:07 +0000</pubDate>
      <link>https://dev.to/ifirestone/arquitectura-de-microservicios-53j4</link>
      <guid>https://dev.to/ifirestone/arquitectura-de-microservicios-53j4</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1667372459510-55b5e2087cd0%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDF8fG1pY3Jvc2VydmljZXN8ZW58MHx8fHwxNzkyNzgzMTQyfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fimages.unsplash.com%2Fphoto-1667372459510-55b5e2087cd0%3Fcrop%3Dentropy%26cs%3Dtinysrgb%26fit%3Dmax%26fm%3Djpg%26ixid%3DM3wxMTc3M3wwfDF8c2VhcmNofDF8fG1pY3Jvc2VydmljZXN8ZW58MHx8fHwxNzkyNzgzMTQyfDA%26ixlib%3Drb-4.1.0%26q%3D80%26w%3D2000" alt="Arquitectura de microservicios" width="2000" height="1125"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Imagina una tienda en línea pequeña. Un solo código, una sola base de datos, un solo despliegue. Los clientes inician sesión, ven productos, pagan y reciben un correo. Funciona, y durante mucho tiempo nadie lo cuestiona.&lt;/p&gt;
&lt;p&gt;Luego la tienda crece y empiezan las preguntas. ¿Por qué un error en la página de productos nos obliga a volver a desplegar el código de pagos? ¿Por qué toda la aplicación se pone lenta cada vez que alguien sube un lote de fotos de productos? En algún momento, alguien dice la palabra: &lt;em&gt;microservicios&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Este artículo sigue a esa tienda. Veremos qué son los microservicios, las pautas que indican cuándo una funcionalidad merece convertirse en uno, qué se gana y cuánto cuesta. No entraremos a fondo en cómo construirlos; esa es una historia para otro día.&lt;/p&gt;
&lt;h2 id="%C2%BFqu%C3%A9-es-realmente-un-microservicio"&gt;¿Qué es realmente un microservicio?&lt;/h2&gt;
&lt;p&gt;Una arquitectura de microservicios divide una aplicación en servicios pequeños e independientes, cada uno responsable de una capacidad del sistema. En lugar de un solo programa que lo hace todo, la tienda pasa a ser un conjunto de programas que se comunican entre sí, normalmente a través de APIs.&lt;/p&gt;
&lt;p&gt;La palabra clave es &lt;em&gt;independiente&lt;/em&gt;. Cada servicio se puede desarrollar, desplegar y escalar por separado. Esa independencia es todo el punto, y también es lo que hace difícil la decisión: solo obtienes los beneficios si las piezas son realmente separables.&lt;/p&gt;
&lt;p&gt;Entonces, ¿cuáles lo son? Recorramos la tienda para averiguarlo.&lt;/p&gt;
&lt;h2 id="%C2%BFqu%C3%A9-funcionalidades-merecen-su-propio-servicio"&gt;¿Qué funcionalidades merecen su propio servicio?&lt;/h2&gt;
&lt;p&gt;No toda funcionalidad justifica un servicio propio. Estas son seis pautas, y cada una aparece a medida que la tienda crece.&lt;/p&gt;
&lt;h3 id="1-la-funcionalidad-puede-valerse-por-s%C3%AD-sola"&gt;1. La funcionalidad puede valerse por sí sola&lt;/h3&gt;
&lt;p&gt;El inicio de sesión y los pagos son los primeros candidatos. Ninguno necesita saber cómo se muestran los productos ni cómo se envían los pedidos. Reciben una petición, hacen un trabajo y devuelven una respuesta.&lt;/p&gt;
&lt;p&gt;Eso es &lt;em&gt;autonomía funcional&lt;/em&gt;: si una funcionalidad puede operar sin estar fuertemente acoplada al resto del sistema, es una buena candidata. La autenticación y la gestión de pagos son ejemplos clásicos.&lt;/p&gt;
&lt;h3 id="2-necesita-escalar-de-forma-distinta"&gt;2. Necesita escalar de forma distinta&lt;/h3&gt;
&lt;p&gt;Ahora la tienda agrega la subida de imágenes. Cada foto de producto se redimensiona y se comprime, y durante una importación grande del catálogo los servidores se calientan. Pero la página de pago no necesita más potencia que antes.&lt;/p&gt;
&lt;p&gt;Escalar toda la aplicación para atender una sola tarea pesada es un desperdicio. Cuando una funcionalidad tiene requisitos de escalado distintos al resto, como un servicio de procesamiento de imágenes que necesita mucho cómputo, un servicio separado te permite escalar solo lo que está bajo presión.&lt;/p&gt;
&lt;h3 id="3-otros-sistemas-tambi%C3%A9n-la-necesitan"&gt;3. Otros sistemas también la necesitan&lt;/h3&gt;
&lt;p&gt;La tienda lanza una segunda marca con su propio sitio web. Ambas necesitan enviar confirmaciones de pedido y restablecimientos de contraseña por correo. Copiar el código de correo al segundo proyecto funcionaría, hasta el día en que una copia recibe una corrección y la otra no.&lt;/p&gt;
&lt;p&gt;Si varios sistemas o aplicaciones usan la misma capacidad, convertirla en un servicio fomenta la reutilización y elimina la duplicación. Un servicio de notificaciones por correo es el ejemplo de siempre.&lt;/p&gt;
&lt;h3 id="4-cambia-a-otro-ritmo"&gt;4. Cambia a otro ritmo&lt;/h3&gt;
&lt;p&gt;El equipo añade recomendaciones de productos con machine learning. Los modelos se reentrenan y se ajustan constantemente, mientras que el flujo de pago cambia unas pocas veces al año. Atarlos al mismo ciclo de releases frena a uno y pone en riesgo al otro.&lt;/p&gt;
&lt;p&gt;Cuando una funcionalidad necesita un ciclo de desarrollo y despliegue distinto al del resto del sistema, debería ser su propio servicio. Un servicio de recomendaciones que necesita actualizaciones frecuentes encaja bien.&lt;/p&gt;
&lt;h3 id="5-corresponde-a-un-dominio-de-negocio-claro"&gt;5. Corresponde a un dominio de negocio claro&lt;/h3&gt;
&lt;p&gt;Mira cómo habla el negocio de sí mismo: catálogo, pedidos, pagos, inventario. En el Diseño Guiado por el Dominio (Domain-Driven Design, DDD), estos son &lt;em&gt;subdominios&lt;/em&gt;: áreas del negocio con su propio lenguaje y sus propias reglas.&lt;/p&gt;
&lt;p&gt;Las funcionalidades que corresponden a un subdominio bien definido son candidatas ideales. Un servicio de inventario en un sistema de comercio electrónico, por ejemplo, refleja cómo el negocio ya piensa.&lt;/p&gt;
&lt;h3 id="6-tiene-el-tama%C3%B1o-adecuado"&gt;6. Tiene el tamaño adecuado&lt;/h3&gt;
&lt;p&gt;Esta es la pauta que la gente olvida. Imagina dividir la tienda tan lejos que "dar formato a un precio" se vuelve un servicio. Ahora cada operación simple requiere una llamada de red, y el sistema es un laberinto.&lt;/p&gt;
&lt;p&gt;Un microservicio debe ser lo bastante pequeño para enfocarse en una tarea, pero lo bastante grande para no fragmentar el sistema en exceso. Si una funcionalidad es trivial, o depende mucho de otras, probablemente no merece ser un servicio.&lt;/p&gt;
&lt;h2 id="lo-que-gana-la-tienda"&gt;Lo que gana la tienda&lt;/h2&gt;
&lt;p&gt;Supongamos que la tienda sigue esas pautas y separa las piezas correctas. ¿Qué cambia?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Escalabilidad.&lt;/strong&gt; El servicio de imágenes escala durante una importación mientras todo lo demás se queda como está.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Flexibilidad tecnológica.&lt;/strong&gt; El servicio de recomendaciones puede usar el lenguaje y las herramientas más adecuados para machine learning, sin imponérselos al resto del sistema.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Desarrollo y despliegue independientes.&lt;/strong&gt; Distintos equipos pueden trabajar en distintos servicios al mismo tiempo, lo que acelera el desarrollo y la entrega continua.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resiliencia.&lt;/strong&gt; Como los servicios están desacoplados, la caída de uno no tumba necesariamente al resto. Si las recomendaciones se caen, los clientes todavía pueden pagar.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reutilización.&lt;/strong&gt; Un servicio bien diseñado, como el de correo, se puede reutilizar en distintos proyectos y contextos.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mantenimiento más fácil.&lt;/strong&gt; Corregir un error o actualizar un servicio no implica tocar toda la aplicación.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="lo-que-paga-la-tienda"&gt;Lo que paga la tienda&lt;/h2&gt;
&lt;p&gt;Si esa fuera toda la historia, todos los proyectos empezarían con microservicios. No lo es.&lt;/p&gt;
&lt;p&gt;Dividir un sistema convierte llamadas a función en llamadas de red, y un solo código en muchas piezas móviles. La tienda ahora necesita monitoreo avanzado para ver qué pasa entre servicios, un versionado cuidadoso para que un servicio no rompa a otro, y un plan para saber cómo se comunican los servicios cuando algo sale mal.&lt;/p&gt;
&lt;p&gt;Esos costos son reales, y caen sobre ti el día que divides. Por eso conviene analizar con cuidado antes de convertir una funcionalidad en un servicio nuevo.&lt;/p&gt;
&lt;h2 id="de-vuelta-a-la-tienda"&gt;De vuelta a la tienda&lt;/h2&gt;
&lt;p&gt;La tienda no necesitó microservicios el primer día. Los necesitó cuando funcionalidades específicas empezaron a tirar en direcciones distintas: otra carga, otro ritmo de releases, otros consumidores. Las seis pautas anteriores son una forma de notar ese momento, y de notar cuándo todavía no ha llegado.&lt;/p&gt;
&lt;p&gt;Usados con intención, los microservicios permiten que un equipo se concentre en la calidad, la escalabilidad y la agilidad. Usados por moda, solo añaden complejidad. Si todavía estás sopesando los pros y contras, &lt;a href="https://blog.ifirestone.dev/monolito-modular-o-microservicios-un-marco-para-decidir-sin-dogmas/" rel="noreferrer noopener"&gt;Monolito modular o microservicios: un marco para decidir sin dogmas&lt;/a&gt; profundiza en esa decisión.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>microservices</category>
      <category>scalability</category>
      <category>systemdesign</category>
    </item>
  </channel>
</rss>
