<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by carlzhou on Medium]]></title>
        <description><![CDATA[Stories by carlzhou on Medium]]></description>
        <link>https://medium.com/@zhouyxamp?source=rss-80eafdb1fac9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LfjNqcfbz68saSnuhltHVw.jpeg</url>
            <title>Stories by carlzhou on Medium</title>
            <link>https://medium.com/@zhouyxamp?source=rss-80eafdb1fac9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:06:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zhouyxamp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Convert your Laravel application to SaaS]]></title>
            <link>https://zhouyxamp.medium.com/convert-your-laravel-application-to-saas-8b235aaca2fb?source=rss-80eafdb1fac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b235aaca2fb</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[database-migration]]></category>
            <category><![CDATA[multi-tenant]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[carlzhou]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 14:48:13 GMT</pubDate>
            <atom:updated>2021-04-08T14:59:38.417Z</atom:updated>
            <content:encoded><![CDATA[<p>You had made an application with Laravel for a customer. Thanks for the rapid development speed provided by Laravel, you finished the job quickly and your customer was quite satisfied, and this customer even recommended the application to others who have the same problem. Although the application was designed for a single customer at the beginning, that’s not a problem: you just need to deploy a new one when a new customer comes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYVDE1GDBLRBf3r8ob7-_g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@whoisdenilo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Who’s Denilo ?</a> on <a href="https://unsplash.com/s/photos/rent?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>You were lucky enough that more and more customers came, but you also found it’s harder and harder to maintain many deployments. Then you wanted to resolve this happiness trouble, you searched “Laravel multi tenancy” or “Laravel SaaS” via Google and found some packages may help, but unfortunately they might require your table have a column like “tenant_id” …</p><p>If you are in the same situation as I was once, I hope this article can give you some idea on how to convert your application to a multi tenancy one without touching your database.</p><h3><strong>The Application</strong></h3><p>Several years ago, a friend of mine asked me to develop an application to simplify his work at hospital. This application would be used for managing education activities, should have admin UI for administrators to manage data and a mobile web UI for students’ usage.</p><p>The architecture of the application was rather straight forward:</p><ul><li>The frontend was in AngularJs 1.x;</li><li>The backend was in Laravel 4.2;</li><li>A single MySQL 5.5 database.</li></ul><p>Redis, Queues, … all were unnecessary. The development was finished in a couple of days. The application worked well for the hospital, word of mouth helped us gained more hospitals over time. Although many features have been added over the years, the architecture remains the same. It’s simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPi_K0txn5a0ofx9hDIq1A.png" /><figcaption>The unsexy application architecture</figcaption></figure><h3><strong>Convert It to SaaS</strong></h3><p>With more deployments done, we started to learn how others do their SaaS applications. Microsoft has a good article on this topic <a href="https://docs.microsoft.com/en-us/azure/azure-sql/database/saas-tenancy-app-design-patterns">here</a> (I can’t find the original article we read, but this one has similar content), we identified that we were actually in the “Standalone single-tenant” model, and we wanted to migrate to “Database-per-tenant” model. “Sharded-multi-tenant” requires column like “tenant_id” to be added in tables, that could involve too much modifications and we don’t want this.</p><p>Our target was to deploy a single copy of application per server. When serving requests, the application could load proper database and application configuration dynamically for the requested hospital. We found there are Laravel packages trying to resolve multi-tenancy issue, but after some try we decided to do it without 3-rd party packages to make the solution simple and clear.</p><p>The following sections describe how we did it.</p><h4><strong>Detect Tenant Information At Runtime</strong></h4><p>First we need to detect the tenant information to correctly load tenant configuration. There are two points to check:</p><ol><li>HTTP request handling;</li><li>Console command execution (e.g., artisan commands, queue workers, scheduled jobs).</li></ol><p>For HTTP request handling, we can detect the tenant by keywords in the URL. In our case every customer has its own domain, so we use domain to make this detection.</p><p>For console commands, we can provide commands an extra option (--tenant) to specify the tenant manually.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8918c25dfa160990cecf7f69532e36da/href">https://medium.com/media/8918c25dfa160990cecf7f69532e36da/href</a></iframe><h4><strong>Adding “--tenant” Option to All Artisan Commands</strong></h4><p>Some Laravel multi-tenancy packages provide commands to migrate database. For example, some package has the following command:</p><pre>php artisan tenants:migrate --tenants=8075a580-1cb8-11e9-8822-49c5d8f8ff23</pre><p>This is ok but the syntax is not that elegant to us. What if we can have these:</p><pre>php artisan --tenant=A migrate<br>php artisan --tenant=B queue:work<br>php artisan --tenant=C schedule<br>php artisan --tenant=D &lt;any customized command&gt;</pre><p>This syntax is much easier to remember as all Laravel developers are familiar with it :).</p><p>“--tenant” option can be added by overriding getArtisan method in <em>App\Console\Kernel</em> class. This is inspired by digging into the implementation of “--env” option. Now all artisan commands have “--tenant” option, the <em>detectConsole</em> method of <em>TenantDetector</em> class above demonstrates how to read it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdabf799ab0c9083cf471d64444c2908/href">https://medium.com/media/cdabf799ab0c9083cf471d64444c2908/href</a></iframe><h4><strong>Load Application Configuration Dynamically</strong></h4><p>Now tenant can be detected, the next step is to load the tenant’s configuration. Laravel’s Config facade could be used for changing configurations at runtime, like below:</p><pre>$tenant = (new TenantDetector)-&gt;detect(app());<br>$tenantConnection = $this-&gt;getTenantConnection($tenant);<br>Config::set(&#39;database.connection&#39;, $tenantConnection);</pre><p>However, this means you have to add such snippet to all HTTP request or command handling logic. Use HTTP middleware or service provider can simplify this work, but that’s far from ideal:</p><ol><li>We need to be careful on the order of HTTP middlewares or service providers, the configuration loading logic should be ran before any other codes that depend on the configuration;</li><li>We can’t add this to Laravel builtin commands, such as php artisan migrate.</li></ol><p>Laravel uses <em>Illuminate\Foundation\Bootstrap\LoadConfiguration</em> class to load configuration on each time it bootstraps. This class is added into the <em>bootstraper</em> arrays of <em>HTTPKernel</em> and <em>ConsoleKernel</em>. Fortunately, <em>bootstraper</em> arrays of both kernels are customizable, our best choice is to add a <em>LoadTenantConfiguration</em> class, and add it into the bootstrap arrays right after <em>LoadConfiguration</em> class.</p><p><em>HttpKernel</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7630a56f40b4879b15ed1124754fbaf/href">https://medium.com/media/c7630a56f40b4879b15ed1124754fbaf/href</a></iframe><p><em>ConsoleKernel</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3da771178e004c16c90b0e57ebb2b713/href">https://medium.com/media/3da771178e004c16c90b0e57ebb2b713/href</a></iframe><p>Implement <em>LoadTenantConfiguration</em> bootstraper class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31f905931ba8726bc46a9e10cbe8ac23/href">https://medium.com/media/31f905931ba8726bc46a9e10cbe8ac23/href</a></iframe><p>In our case the database and password are configured in a fixed pattern, so this method is simple here. You can customize <em>loadConfiguration</em> as you wish, e.g., load the configuration from a central database or load any other tenant specific configurations.</p><p>The bootstrap code above checks if the application is running artisan config:cache command. We won’t want tenant specific configuration be saved in the config cache, as config cache should only contains common configurations for all tenants.</p><h4><strong>Command Scheduling</strong></h4><p>Now you can add tenant in schedule command like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92beb938ea09ca6eb8906cd0bf8d68b0/href">https://medium.com/media/92beb938ea09ca6eb8906cd0bf8d68b0/href</a></iframe><p>As Laravel start a new process to execute scheduled command, tenant parameter needs to be passed into schedule command manually. So we need to update <em>App\Console\Kernel</em> like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0c013699bed6b60f74ab8f0b8b10787/href">https://medium.com/media/f0c013699bed6b60f74ab8f0b8b10787/href</a></iframe><h4>Queue Workers</h4><p>As queue workers are started by artisan command, we also need to add tenant information in the command to make sure it loads proper configurations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef57fc70ef9af19d326ee8badf2154f5/href">https://medium.com/media/ef57fc70ef9af19d326ee8badf2154f5/href</a></iframe><h4>Migration</h4><p>Now you may also need to update your deployment scripts to specify the tenant for database migration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34faa3e8540f154f45f4b06f4d0592b2/href">https://medium.com/media/34faa3e8540f154f45f4b06f4d0592b2/href</a></iframe><p>That’s it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b235aaca2fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Laravel Auth Guard]]></title>
            <link>https://zhouyxamp.medium.com/understanding-laravel-auth-guard-50d5d4c0f33?source=rss-80eafdb1fac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/50d5d4c0f33</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[carlzhou]]></dc:creator>
            <pubDate>Mon, 05 Apr 2021 13:29:44 GMT</pubDate>
            <atom:updated>2021-04-08T13:27:46.765Z</atom:updated>
            <content:encoded><![CDATA[<p>Laravel provides an easy to use authentication system, but it confused me a little when the first time I wanted to extend an application to have different type of users, each with its own table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8wYkQ3asNLy_PXMslE4b3w.jpeg" /></figure><p>Laravel has defined some guards in config/auth.php out of the box:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93480f5babef003781d87649562e9fa/href">https://medium.com/media/e93480f5babef003781d87649562e9fa/href</a></iframe><p>This presents three related concepts: guard, driver and provider. Laravel has a good document on the topic of authentication, but it’s a bit lengthy and I felt confusion when I tried to configure them to support different users with separate tables. I hope this article can give you a quick understanding of the framework if you are also confused.</p><h3><strong># Auth Guard</strong></h3><blockquote><a href="https://en.wikipedia.org/wiki/Authentication">Wikipedia “Authentication”</a></blockquote><blockquote>In contrast with <a href="https://en.wikipedia.org/wiki/Identity_(philosophy)">identification</a>, the act of indicating a person or thing’s identity, authentication is the process of verifying that identity.</blockquote><p>Laravel auth <strong><em>guard</em></strong> is responsible for authenticating a user. It takes some form of input and validate user identity in it. How to make the validation is implemented by a <strong><em>driver</em></strong>. The driver may use a user <strong><em>provider</em></strong> to retrieve user information.</p><p>Normally we use the API provided by auth guard to interact with the authentication system, like this:</p><pre>$user = auth()-&gt;user();</pre><h3># Auth Guard Driver</h3><p>Driver knows how to authenticate user in a specific manner. For example, the session driver used by the “web” guard uses session ID for authentication. The session ID is encrypted and stored in a cookie named “laravel_session” by default. Session driver checks and decrypts session ID from this cookie, and then uses the configured provider to retrieve user information.</p><p>The contract for auth guard is<em> </em><a href="https://github.com/laravel/framework/blob/8.x/src/Illuminate/Contracts/Auth/Guard.php"><em>Illuminate\Contracts\Auth\Guard</em></a><em>. </em>Session driver <a href="https://github.com/laravel/framework/blob/8.x/src/Illuminate/Auth/SessionGuard.php"><em>Illuminate\Auth\SessionGuard</em></a> is one implementation<em>. </em>The following shows the main procedure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ced906585a3aec5a40b2f3d407fe944/href">https://medium.com/media/5ced906585a3aec5a40b2f3d407fe944/href</a></iframe><p>If your project uses JWT, you might also have been using the great <a href="https://github.com/tymondesigns/jwt-auth">tymon/jwt-auth</a> package. It contains a class <a href="https://github.com/tymondesigns/jwt-auth/blob/develop/src/JWTGuard.php"><em>Tymon\JWTAuth\JWTGuard</em></a> implementing how to authenticate user by using JWT token in HTTP request.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/166515d1daf8840546f463a0770011d9/href">https://medium.com/media/166515d1daf8840546f463a0770011d9/href</a></iframe><h3># User Provider &amp; Driver Configuration</h3><p>The last piece of the configuration of auth guard is user provider. Actually, “provider” is not required in the configuration. It is required only when the driver requires it. Laravel document contains examples for drivers that do not need this configuration.</p><p>The configuration value for a guard will be passed into its driver as the driver’s configuration. In the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a88d9e2b3b484d3ea325bcfef98c5e/href">https://medium.com/media/c3a88d9e2b3b484d3ea325bcfef98c5e/href</a></iframe><p>JWT driver will receive:</p><pre>[<br>    &#39;driver&#39; =&gt; &#39;jwt&#39;,<br>    &#39;provider&#39; =&gt; &#39;users&#39;,<br>    &#39;hash&#39; =&gt; false,<br>]</pre><p>as it’s configuration. This configuration is passed as $config in the following implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eae3bee4009944a8cbc11cbc4145795/href">https://medium.com/media/9eae3bee4009944a8cbc11cbc4145795/href</a></iframe><p>So the scheme of guard configuration depends on its driver.</p><h3># Different Type of Users in Different Tables</h3><p>In previous example, we have two types of user: admin and user. For admins session driver is used, and for users JWT driver is used. We could use them in auth middleware like this:</p><pre># protecting admin routes<br>Route::group([&#39;middleware&#39; =&gt; &#39;auth:admin&#39;], function () {</pre><pre># protecting user routes<br>Route::group([&#39;middleware&#39; =&gt; &#39;auth:user&#39;], function () {</pre><p>In our controller, we could use auth guard to get user information:</p><pre>$user = auth()-&gt;user();</pre><p>But wait! Now we have two kinds of auth guards, which one is used in this code? We know there’s a default guard configured in config/auth.php, is that one?</p><p>The answer is Laravel is smart enough to choose a proper guard. When authentication middleware authenticates a user via a guard specified in the route, it changes the default guard to that guard dynamically. So later <em>auth()-&gt;user()</em> call uses the right guard.</p><p>If you want to specify guard explicitly, you can do it like below:</p><pre># use admin guard explicitly<br>$user = auth(&#39;admin&#39;)-&gt;user();</pre><pre># use user guard explicitly<br>$user = auth(&#39;user&#39;)-&gt;user();</pre><p>Hope this article can be helpful, thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50d5d4c0f33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>