【发布时间】:2018-03-22 23:40:58
【问题描述】:
我对 Laravel 还是很陌生,并且已经完成了一些基本的 laracast。现在我开始了我的第一个 laravel 项目,但我被困在如何使用我的第一个包“Landlord”上。基本上我需要在我的应用程序中设置多租户。我有一个公司表和一个用户表,用户表有一个 company_id 列。当公司注册时,它会成功创建公司并将 company_id 附加到用户。
我认为 Landlord 是实现多租户应用程序的最佳方式,因此我按照安装说明进行操作,现在我将其包含在我的应用程序中。
但是,USAGE 部分的第一行说: 重要提示:房东是无国籍的。这意味着当您调用 addTenant() 时,它只会作用于当前请求。
确保您添加租户的方式是 发生在每个请求上,并且在您需要模型范围之前,例如在 中间件或作为 OAuth 等无状态身份验证方法的一部分。
看起来我需要附加一个Landlord::addTenant('tenant_id', 1); 门面。
这可能是一个我忽略的非常简单的答案,但是使用addTenant 的最佳位置在哪里,我是否必须在每个控制器或模型中重新声明它?我应该在用户登录时附加它,在我的路由中使用它还是用作中间件?如果它是一个中间件,那么为了从当前用户中提取 company_id 并将其与addTenant 一起使用,以下是正确的吗?
中间件:
public function handle($request, Closure $next){
$tenantId = Auth::user()->tenant_id;
Landlord::addTenant('tenant_id', $tenantId);
return $next($request);
}
更新
这是我的中间件 (MultiTenant.php)
<?php
namespace App\Http\Middleware;
use Closure;
use App\User;
use Illuminate\Support\Facades\Auth;
class MultiTenant
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::check()) {
$tenantId = Auth::user()->company_id;
Landlord::addTenant('company_id', $tenantId); // Different column name, but same concept
}
return $next($request);
}
}
我的路线/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::group(['middleware' => ['multitenant']], function () {
Route::get('/home', 'HomeController@index');
//Clients
Route::resource('clients', 'ClientController');
});
我的 Client.php 模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use HipsterJazzbo\Landlord\BelongsToTenants;
class Client extends Model
{
use BelongsToTenants;
//
protected $fillable = [
'organization',
];
}
https://github.com/HipsterJazzbo/Landlord#user-content-usage
【问题讨论】:
-
如果所有包含租户数据的表都具有
tenant_id键,那么它们都将使用全局附加全局范围WHEREtenant_id = ID进行查询(当然如果它们具有BelongsToTenants特征) .是的,中间件是添加租户的最佳场所,恕我直言
标签: php laravel laravel-5.2