


Teach you how to make your Laravel application multi-tenant in a few minutes
The following tutorial column will introduce to you how to make Laravel applications have multi-tenant functions in a few minutes. I hope it will be helpful to friends in need!
In this tutorial, we will useTenancy for Laravel package to make Laravel applications multi-tenant.
It is a multi-tenant software package that allows your Laravel application to be multi-tenant No need to copy additional code
. It's as plug-and-play as a rental package.
Side note: In this tutorial, we'll cover the most common setup - multi-database tenancy on multiple domains. If you need a different setup, this is 100% possible. Just check out the package.
How it worksWhat is unique about this package is that it does not force you to write your application in a specific way. You can write your application as you are used to and it will automatically generate multi-tenancy under the hood. You can even integrate packages into existing applications.
The following is how it works:
1. When the server receives a user request
2. The program can identify which tenant the request belongs to through the request. (Through the main domain name, subdomain name, path, request header, query parameters, etc.)3. The program will switch from the
default database link to the current tenant link.
4. Any database calls, cache calls, queue calls, and other operations will automatically match the tenant and switch.
Installation
The first step is to install the package through composer. The command is as follows:
composer require stancl/tenancy
Then, execute the
tenancy:installcommand as follows:
php artisan tenancy:install
This operation will generate the following files: migration files, configuration files, routing files and a service provider. Let us set up the database and perform database migration through the following command:
php artisan migrate
Then register the service provider in
config/app.php. Please make sure to place the code in the following location:
/* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, App\Providers\TenancyServiceProvider::class, // <p>Now, we create a custom tenant model. The package is unrestricted, so to use a separate database and domain we need to create a slightly customized tenant model. Create a <code>app/Tenant.php</code> file with the following code: </p><pre class="brush:php;toolbar:false"><?php namespace App; use Stancl\Tenancy\Database\Models\Tenant as BaseTenant; use Stancl\Tenancy\Contracts\TenantWithDatabase; use Stancl\Tenancy\Database\Concerns\HasDatabase; use Stancl\Tenancy\Database\Concerns\HasDomains; class Tenant extends BaseTenant implements TenantWithDatabase { use HasDatabase, HasDomains; }
Now we tell the package to use this model for tenants: <pre class="brush:php;toolbar:false">// config/tenancy.php file
'tenant_model' => \App\Tenant::class,</pre>
Two parts
The package treats your application as two separate parts:
central application - hosts the login page, possibly a central dashboard to manage tenants, etc.tenant Application - This is the part used by your tenants. This is most likely where most of the business logic resides- Split the Application
- Now that we understand these two parts, let’s split the application accordingly.
Central app
First let’s make sure the central app is only accessible on the central domain.
Go to
app/Providers/RouteServiceProvider.phpand make sure your
web and api
routes are only loaded on the central domain: <pre class="brush:php;toolbar:false">protected function mapWebRoutes()
{
foreach ($this->centralDomains() as $domain) {
Route::middleware('web')
->domain($domain)
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
}
protected function mapApiRoutes()
{
foreach ($this->centralDomains() as $domain) {
Route::prefix('api')
->domain($domain)
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}
protected function centralDomains(): array
{
return config('tenancy.central_domains');
}</pre>
Now go to your file config/tenancy.php
and actually add the central domain.
I'm using Valet, so for me the central domain is saas.test
and the tenant domains are
and bar .saas.test
is an example. So we set the
central_domains
key:
'central_domains' => [ 'saas.test', // Add the ones that you use. I use this one with Laravel Valet. ],
Tenant app Now comes the fun part. This part is almost too easy.
To make some code tenant-aware, you just need to do the following:
Move migrations to thetenant/
directory- Move the routes to the
tenant.php
routing file That's it.
Migrating in that specific folder and including a route in that specific route file will notify the package that identifies the tenant on that route.
If you have an existing application, use your code to do this. If you are using a brand new application, please follow the following example:
By default, your tenant routes look like this:
Route::middleware([ 'web', InitializeTenancyByDomain::class, PreventAccessFromCentralDomains::class, ])->group(function () { Route::get('/', function () { return 'This is your multi-tenant application. The id of the current tenant is ' . tenant('id'); }); });
These routes can only be used in the tenant (non-hub) domain Access on -
PreventAccessFromCentralDomainsmiddleware enforces this.
Let's make a small change to dump all the users in the database so we can actually see multi-tenancy working. Add this to the middleware group: <pre class="brush:php;toolbar:false">Route::get('/', function () {
dd(\App\User::all());
return 'This is your multi-tenant application. The id of the current tenant is ' . tenant('id');
});</pre>
Now, migrate. Just move the migrations related to the tenant application into the
directory.
因此,对于我们的示例:要使用户进入租户数据库,让我们将users表迁移移至数据库/迁移/租户。这将防止在中央数据库中创建表,而是在创建租户时在租户数据库中创建表。
尝试一下
现在让我们创建一些租户。
我们还没有可供租户注册的登录页面,但是我们可以在修补程序中创建他们!
因此,让我们打开php artisan tinker
并创建一些租户。租户实际上只是模型,因此您可以像其他任何Eloquent模型一样创建它们。
请注意,我们在 这里使用域标识因此,请确保您使用的域指向您的应用程序。我正在使用代客,所以我正在*.saas.test
用于租户。如果使用php artisan serve
,则可以使用foo.localhost
。
>> $tenant1 = Tenant::create(['id' => 'foo']); >> $tenant1->domains()->create(['domain' => 'foo.saas.test']); >>> >> $tenant2 = Tenant::create(['id' => 'bar']); >> $tenant2->domains()->create(['domain' => 'bar.saas.test']);
现在,我们将在每个租户的数据库中创建一个用户:
App\Tenant::all()->runForEach(function () { factory(App\User::class)->create(); });
就是这样- 我们有一个多租户应用程序!
如果您访问 foo.saas.test
(或与您的环境相当),则会看到用户转储。
如果访问bar.saas.test
,您将看到不同用户的转储 。数据库是100%分离的,我们使用的代码 —App\User::all()
— 根本不需要了解租约!这一切都会在后台自动发生。您只需像以前那样编写应用程序,而不必考虑自己的范围界定,并且一切都正常。
当然,现在,租户应用程序中将有一个更复杂的应用程序。仅转储用户的SaaS可能用处不大。这就是您的工作-编写将由租户使用的业务逻辑。包装将处理其余部分。
不过,Tenancy for Laravel 项目的帮助并没有到此结束。该软件包将为您完成与多租户相关的所有繁重工作。但是,如果您要构建SaaS,则仍然需要自己编写计费逻辑,入门流程和类似的标准内容。如果您有兴趣,该项目还提供了一个优质产品:multi-tenant SaaS boilerplate。它旨在通过为您提供通常需要编写的SaaS功能来节省您的时间。所有这些都打包在一个随时可以部署的多租户应用程序中。
原文地址:https://laravel-news.com/multi-tenant
译文地址:https://learnku.com/laravel/t/47951
The above is the detailed content of Teach you how to make your Laravel application multi-tenant in a few minutes. For more information, please follow other related articles on the PHP Chinese website!

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

LaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),