These docs are for v2.0. Click to read the latest docs for v5.

Eloquent facade, tenant & system model

A best practice in Laravel land for package development is to not use root facades at all. Although this documentation mentions in its configuration section to set up the Eloquent facade to use the TenantModel, I recommend against it.

A better way to structure your app is to create two (or three) abstract Models of your own; TenantModel, SystemModel and perhaps a DefaultModel.

<?php

namespace App;

use Hyn\Tenancy\Abstracts\Models\TenantModel as ParentModel;

abstract class TenantModel extends ParentModel
{
}
<?php

namespace App;

use Hyn\Tenancy\Abstracts\Models\SystemModel as ParentModel;

abstract class SystemModel extends ParentModel
{
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

abstract class DefaultModel extends Model
{
}

The approach mentioned allows you to use these classes in your code and knowing exactly which connection they'll use. By not using the models provided by this package you can overrule any logic within the Laravel eloquent model without touching them. Also this approach lets you overrule basic Eloquent model behavior per connection.

Example User

So how would that approach be implemented? Let's take a look at the User model.

<?php

namespace App;

class User extends TenantModel
{
}

The User inside your app are now being loaded from the tenant connection. Authentication therefore is also being run while using the tenant database connection.

❗️

Make sure to run the users table migration on the tenants before switching the User class to use the tenant connection.

🚧

Please note no import (use statement) is needed, because the TenantModel resides in the same namespace.