Laravel tenant early initialization for multi db system
I am building a Laravel multi-tenant (each tenant has a separated db), with tenancyforlaravel package. Now I am building a structure where users can create their own entities like: Cars, Jobs etc. I have done this successfully on the central DB, but I am facing a problem when I do this structure for tenants. First, I create the relevant fields that will be part of an entity, then I create the entity and add the fields I just created, at this moment migrations, models, controllers, and resources are created and a db table looks like this:
select * from entities;
+----+------+-------+-----------+---------------------+---------------------+
| id | name | order | is_active | created_at | updated_at |
+----+------+-------+-----------+---------------------+---------------------+
| 1 | jobs | 0 | 1 | 2024-05-23 11:51:51 | 2024-05-23 11:51:51 |
+----+------+-------+-----------+---------------------+---------------------+
This is on tenant DB. NOTE: each tenant db has this prefix: tenant and the full table name will be tenant+profilename, in my case: tenantagency;
So far so good. The problem comes when I try to add routes for this entity, and in practice i do something like this:
// tenant.php
Route::middleware([
'web',
InitializeTenancyByDomain::class,
PreventAccessFromCentralDomains::class,
InitializeTenancy::class,
])->group(function () {
....
$tenant->get('entity', $baseViewController);
$tenant->get('fields', $baseViewController);
// Include custom web entity routes
require __DIR__.'/tenant/entities/entityRoutesWEB.php';
....
});
// .../entityRoures/php
$entities = Entities::all();
// dd($entities);
foreach ($entities as $entity) {
$entityName = strtolower($entity->name);
$controllerName = 'App\Http\Controllers\API\Tenant\' . ucfirst($entityName) . 'Controller';
// Define routes for this entity
Route::get("/{$entityName}", [BaseViewController::class, 'index']); // Fetch data for the entity
}
So my problem is here: `$entities = Entities::all();
// dd($entities);` this is getting the entities from the central db.
// /Tenant/EntitiesModel.php
namespace App\Models\Tenant\Entities;
// /Central/EntitiesModel.php
namespace App\Models\Central\Entities;
NOTE: The same logic I have used for the central DB and it works.
Please or to participate in this conversation.