bvharen/laravel-subdomain

2.0 2021-01-20 10:57 UTC

This package is auto-updated.

Last update: 2024-09-20 19:04:30 UTC


README

轻松设置动态子域名,这些子域名注册在您的应用程序的模型上,例如 company1.myapp.com

安装

您可以通过以下命令使用 composer 安装此包:

composer require kofoworola/laravel-subdomain

*在 Laravel 5.5 及以下版本中,将以下内容添加到您的 providers 和 aliases 数组中

'providers'=>[
    //...
    kofoworola\Subdomains\ServiceProvider::class
]
'aliases' => [
    //..
    'Subdomains': kofoworola\Subdomains\Facade\Subdomains::class
] 

然后运行 php artisan vendor:publish 来发布配置文件

配置

config/subdomains.php 文件

<?php
return [
    /*
     * The name of the parameter to be used for subdomains
     */
    'subdomain' => 'app',

    /*
     * The model that owns subdomains
     */
    'model' => '\App\Company',

    /*
     * The column in the user
     */
    'column' => 'slug',

    'middleware' => [

        /*
         * The user model to perform authentication checking on
         */
        'user_model' => '\App\User',

        /*
         * The function/relationship that defines the link between the user model and the subdomain owner 
         * Can return Collection/Array of Models or single model
         */
        'function' => 'companies',
    ]
];

一旦发布了包,您就可以将其配置设置到应用程序的设置中

使用

在设置好捕获子域名的路由后,例如

Route::group(['domain' => '{app}.subdomains.app','middleware' => ['auth']],function (){
    Route::get('/','SubController@index')->name('index');
    Route::get('/{param}',SubController@param)->name('param')
    //Rest of routes
});

确保所有分配给子域名的控制器都扩展了 \kofoworola\Subdomains\Controller\SubdomainController

use kofoworola\Subdomains\Controller\SubdomainController;

class SubController extends SubdomainController
{
    public function index(){
        return 'hello';
    }

    /*
     * No need to get the subdomain value via parameter for every method redundantly
     * You can get it through the subdomain facade when needed
     */ 
    public function param($param){
        return $param;
    }
}

父控制器会自动从参数列表中移除子域名参数,因此您无需每次想要获取另一个参数时都将其添加到参数列表中

门面

使用 kofoworola\Subdomains\Facade\Subdomains 门面,您可以访问辅助函数

获取参数名称

使用 Subdomains::name() 获取子域名参数的名称

获取子域名的值

使用 Subdomains::value() 获取子域名参数的值

获取子域名的所有者

使用 Subdomains::owner() 获取拥有当前子域名的模型实例

检查用户是否有权访问子域名

Subdomains::ownsModel($user = null) 根据用户是否有权访问子域名返回 true 或 false

如果没有传递用户,则使用当前登录用户

获取子域名路由

//If model is passed the value of its subdomain will be used to generate route
//If not the current owner will be used

Subdomains::route('route.name',$params = [],$model = null);

可用于生成子域名链接

中间件

您还可以将 \kofoworola\Subdomains\Middleware\HasSubdomain 中间件添加到您的路由中。首先在您的 Kernel 中注册它

protected $routeMiddleware = [
        //Rest of middlewares
        'subdomain' => \kofoworola\Subdomains\Middleware\HasSubdomain::class,
    ];

然后将它添加到您的路由中

Route::group(['domain' => '{app}.subdomains.app','middleware' => ['auth','subdomains']],function (){
    //Rest of routes
});

该中间件将负责验证

  • 子域名是否存在
  • 当前用户是否有权访问子域名