Search code examples
laravelmulti-tenantmulti-database

Is that possible to initialize all the tenants DB at once and take all the records in a table? Laravel Multi tenant


enter image description here

As my diagram, I want to get all the records of table 1 in every tenants from the central domain side. Is that possible to initialize all the tenants at once and take all the records?

Or should I initialize tenants one by one and push records to an array?

I am using the tenancyforlaravel (archtechx/tenancy) package

Updated 1

In tenancyforlaravel tenancy package has a feature to connect tenant DB.It is called initialization. Normally It automatically identifies the database and initializes it by domain address. Also can manually initializes but need to give tenant id. Source link


Solution

  • Finally, I figure out how to do that after long days. It is very very easy with this package. There is a helper function. Only need to use this runForMultiple helper function. below has the example code,

    tenancy()->runForMultiple(null, function (Tenant $tenant) {
            
            foreach (Product::get() as $product) {
                array_push($this->products, [
                    'shop_id' => $tenant->id,
                    'shop_name' => $tenant->name,
                    'id' => $product->id,
                    'name' => $product->name,
                ]);
            }
    
        });