Skip to main content

composer.json

Open in GitHub
{
"require": {
"php": "^7.4|^8.0",
//
"spatie/laravel-multitenancy": "^1.0",
},
}

app/Listeners/TenantAuthenticated.php

Open in GitHub
use App\Models\Tree;
use Illuminate\Auth\Events\Authenticated;
use Illuminate\Support\Facades\DB;
use Spatie\Multitenancy\Models\Concerns\UsesLandlordConnection;
use Spatie\Multitenancy\Models\Tenant;
 
class TenantAuthenticated
{
use UsesLandlordConnection;
 
public function handle(Authenticated $event)
{
$user = auth()->user();
$company = DB::connection($this->getConnectionName())
->table('user_company')
->where('user_id', $user->id)
->select('company_id')
->first();
if($company) {
$tree = Tree::where('company_id', $company->company_id)->first();
$tenant = Tenant::where('tree_id', $tree->id)->first();
$tenant->makeCurrent();
}
}
}

app/Listeners/TenantLogout.php

Open in GitHub
use App\Models\Tree;
use Illuminate\Auth\Events\Logout;
use Illuminate\Support\Facades\DB;
use Spatie\Multitenancy\Models\Concerns\UsesLandlordConnection;
use Spatie\Multitenancy\Models\Tenant;
 
class TenantLogout
{
use UsesLandlordConnection;
 
public function handle(Logout $event)
{
$user = auth()->user();
if($user) {
$company = DB::connection($this->getConnectionName())
->table('user_company')
->where('user_id', $user->id)
->select('company_id')
->first();
if($company) {
$tree = Tree::where('company_id', $company->company_id)->first();
$tenant = Tenant::where('tree_id', $tree->id)->first();
session()->flush();
$tenant->forgetCurrent();
}
 
}
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.