I am building a SAAS, where there is a super admin, which create branches (tenants), and those branches have resources (Customers, Documents....), I am using multi db to achieve tenancy (provided by the package).
When I create customer in Branch, its synced between the branch and the central db, e.g. I create customer in branch, the customer is created in central db as well and the entry is created in the pivot table (tenant_customers). Which proves I have setup the syncing correctly. But the customer is not synced to branch 2, that customer should be copied to all the other branches as well.
Here is the Central Customer Model Code:
class Customer extends AbstractCustomer implements SyncMaster
{
use CentralConnection, ResourceSyncing;
public function tenants(): BelongsToMany
{
return $this->belongsToMany(Branch::class, 'tenant_customers', 'global_id', 'tenant_id', 'global_id')
->using(TenantPivot::class);
}
public function getTenantModelName(): string
{
return TenantCustomer::class;
}
public function getGlobalIdentifierKey()
{
return $this->getAttribute($this->getGlobalIdentifierKeyName());
}
public function getGlobalIdentifierKeyName(): string
{
return 'global_id';
}
public function getCentralModelName(): string
{
return static::class;
}
public function getSyncedAttributeNames(): array
{
return $this->fillable;
}
}
Here is the Tenant Customer Model:
class Customer extends AbstractCustomer implements Syncable
{
use ResourceSyncing;
public function getGlobalIdentifierKey()
{
return $this->getAttribute($this->getGlobalIdentifierKeyName());
}
public function getGlobalIdentifierKeyName(): string
{
return 'global_id';
}
public function getCentralModelName(): string
{
return CentralCustomer::class;
}
public function getSyncedAttributeNames(): array
{
return $this->fillable;
}
}
Here is the store method code in Customer Controller:
public function store(StoreCustomerRequest $request)
{
$validatedData = $request->validated();
$customer = new Customer($validatedData);
$customer->save();
return redirect()->route('tenant.customers.create', tenant('id'))
->with([
'success', 'New Customer has been added!'
]);
}
There is this code in the docs here https://tenancyforlaravel.com/docs/v3/synced-resources-between-tenants:
$user = CentralUser::create(...);
$user->tenants()->attach($tenant);
so this means for all the branches I have to attach manually, I tried it and get the following error:
Attempt to read property prepare on null.