diff --git a/README.md b/README.md index 859bc69..5c10e64 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,15 @@ Impersonate::make('impersonate') ->guard('another-guard') ->redirectTo(route('some.other.route')); ``` + +#### Setting a Custom Impersonation Record + +You can customize the impersonation target by setting a specific impersonation record. This is particularly useful when the target user is related to another entity, and you need to specify which user should be impersonated. + +```php +Impersonate::make('impersonate') + ->setImpersonateRecord(fn($record) => $record->user); +``` ### 2. Add the page action diff --git a/src/Concerns/Impersonates.php b/src/Concerns/Impersonates.php index a5482e8..83a8f37 100644 --- a/src/Concerns/Impersonates.php +++ b/src/Concerns/Impersonates.php @@ -16,6 +16,8 @@ trait Impersonates protected Closure|string|null $backTo = null; + protected Closure|null $impersonateRecord = null; + public static function getDefaultName(): ?string { return 'impersonate'; @@ -86,4 +88,16 @@ public function impersonate($record): bool|Redirector|RedirectResponse return redirect($this->getRedirectTo()); } + + public function setImpersonateRecord(Closure $record): static + { + $this->impersonateRecord = $record; + + return $this; + } + + public function getImpersonateRecord() + { + return $this->evaluate($this->impersonateRecord); + } } diff --git a/src/Pages/Actions/Impersonate.php b/src/Pages/Actions/Impersonate.php index 5183604..99db339 100644 --- a/src/Pages/Actions/Impersonate.php +++ b/src/Pages/Actions/Impersonate.php @@ -16,7 +16,7 @@ protected function setUp(): void $this ->label(__('filament-impersonate::action.label')) ->icon('impersonate-icon') - ->action(fn ($record) => $this->impersonate($record)) - ->hidden(fn ($record) => !$this->canBeImpersonated($record)); + ->action(fn ($record) => $this->impersonate($this->getImpersonateRecord() ?? $record)) + ->hidden(fn ($record) => ! $this->canBeImpersonated($this->getImpersonateRecord() ?? $record)); } } diff --git a/src/Tables/Actions/Impersonate.php b/src/Tables/Actions/Impersonate.php index 01ac57e..32aa378 100644 --- a/src/Tables/Actions/Impersonate.php +++ b/src/Tables/Actions/Impersonate.php @@ -17,7 +17,7 @@ protected function setUp(): void ->label(__('filament-impersonate::action.label')) ->iconButton() ->icon('impersonate-icon') - ->action(fn ($record) => $this->impersonate($record)) - ->hidden(fn ($record) => !$this->canBeImpersonated($record)); + ->action(fn ($record) => $this->impersonate($this->getImpersonateRecord() ?? $record)) + ->hidden(fn ($record) => ! $this->canBeImpersonated($this->getImpersonateRecord() ?? $record)); } }