Skip to content

Commit

Permalink
Merge pull request #9 from henryavila/disable-automatically-set-user-…
Browse files Browse the repository at this point in the history
…owner

disable-automatically-set-user-owner
  • Loading branch information
henryavila authored Sep 27, 2023
2 parents 20a529d + 77c94c0 commit 5f13485
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 11 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "henryavila/laravel-nova-multitenancy",
"version": "3.1.0",
"version": "3.2.0",
"description": "Integrate the multi tenancy single database in Laravel Nova.",
"keywords": [
"henryavila",
Expand Down
8 changes: 8 additions & 0 deletions config/nova-multitenancy.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@
// This invokable class will be executed after the Tenant has been set as current tenant
'invoke_after_tenant_selection' => [],

// If you want to don't automatically set user_id with the auth user when creating tenant model,
// add in this array the classes that will not have this functionality
'ignore_set_owner_user_for_classes' => [],

// By default, all models that has the Trait ModelWithTenant and contains the user_id column,
// will have this value populated with the id of the authenticated user. If you want to disable this feature, set this to false
'automatically_set_owner_user_for_classes' => true,

/*
* This class is responsible for determining which tenant should be current
* for the given request.
Expand Down
24 changes: 14 additions & 10 deletions src/Observers/ModelWithTenantObserver.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,21 @@ public function creating(Model $model)
$model->setAttribute('tenant_id', Tenant::current()->id);
}

if ($modelHasUser && empty($model->getAttribute('user_id'))) {
/** @var User $authenticatedUser */
$authenticatedUser = Auth::user();

if ($authenticatedUser) {
$userId = $authenticatedUser->id;
} else {
throw new Exception('The model "'.get_class($model).'" must be linked to a user. No authenticated user found');
}
$automaticallySetModelOwner = config('nova-multitenancy.automatically_set_owner_user_for_classes') !== false;
if ($automaticallySetModelOwner && $modelHasUser && empty($model->getAttribute('user_id'))) {

if (! in_array($model::class, config('nova-multitenancy.ignore_set_owner_user_for_classes'))) {
/** @var User $authenticatedUser */
$authenticatedUser = Auth::user();

$model->setAttribute('user_id', $userId);
if ($authenticatedUser) {
$userId = $authenticatedUser->id;
} else {
throw new Exception('The model "'.get_class($model).'" must be linked to a user. No authenticated user found');
}

$model->setAttribute('user_id', $userId);
}
}
}
}

0 comments on commit 5f13485

Please sign in to comment.