【发布时间】:2021-05-03 13:47:12
【问题描述】:
在我的 Laravel-5.8 应用程序中,我有一个使用单个数据库的多公司应用程序。每个表都有一个从公司表派生的 company_id,如下所示:
id | company_name | subdomain
1 | Main |
2 | Company1 | company1
3 | Company2 | company2
Main=> localhost:8888/myapp
Company1=>localhost:8888/company1.myapp
Company2=>localhost:8888/company2.myapp
我创建了一个中间件:
class VerifyDomain
{
public function handle($request, Closure $next)
{
$domain == "myapp"; // your company app name
$path = $request->getPathInfo(); // should return /company1.myapp or /company2.myapp or /myapp
if (strpos($path, ".") !== false) { // if path has dot.
list($subdomain, $main) = explode('.', $path);
if(strcmp($domain, $main) !== 0){
abort(404); // if domain is not myapp then throw 404 page error
}
} else{
if(strcmp($domain, $path) !== 0){
abort(404); // if domain is not myapp then throw 404 page error
}
$subdomain = ""; // considering for main domain value is empty string.
}
$company = Company::where('subdomain', $subdomain)->firstOrFail(); // if not found then will throw 404
$request->session()->put('subdomain', $company); //store it in session
return $next($request);
}
}
我已经在 route/web.php 中有两 (2) 个路由组,wgich 看起来像这样:
Route::get('/', ['as' => '/', 'uses' => 'IndexController@getLogin']);
Auth::routes();
Route::get('/dashboard', 'HomeController@index')->name('dashboard');
// Config Module
Route::group(['prefix' => 'config', 'as' => 'config.', 'namespace' => 'Config', 'middleware' => ['auth']], function () {
Route::resource('countries', 'ConfigCountriesController');
Route::resource('nationalities', 'ConfigNationalitiesController');
});
// HR Module
Route::group(['prefix' => 'hr', 'as' => 'hr.', 'namespace' => 'Hr', 'middleware' => ['auth']], function () {
Route::resource('designations', 'HrDesignationsController');
Route::resource('departments', 'HrDepartmentsController');
Route::resource('employee_categories', 'HrEmployeeCategoriesController');
});
我有 2 个问题:
- 如果 subdomain 字段为 null,则路由应针对主域:Main=> localhost:8888/myapp else localhost:8888/company1.myapp 或 localhost:8888/company2.myapp
2.我如何将上面的路线组容纳到这个:
Route::domain('localhost:8888/myapp')->group(function () {
Route::get('/', function ($id) {
//
});
});
Route::domain('localhost:8888/{subdomain}.myapp')->group(function () {
Route::get('/', function ($company_name, $id) {
$company = Company::where('subdomain', $subdomain)->firstOrFail();
// send the value of $company to data to send different view data
});
});
【问题讨论】:
标签: laravel