TenantAtlas/app/Filament/Concerns/ScopesGlobalSearchToWorkspace.php
2026-02-01 12:19:57 +01:00

54 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Filament\Concerns;
use App\Models\User;
use App\Models\Workspace;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Database\Eloquent\Builder;
trait ScopesGlobalSearchToWorkspace
{
/**
* The Eloquent relationship name used to scope records to the current workspace.
*/
protected static string $globalSearchWorkspaceRelationship = 'workspace';
public static function getGlobalSearchEloquentQuery(): Builder
{
$query = static::getModel()::query();
if (! static::isScopedToTenant()) {
$panel = Filament::getCurrentOrDefaultPanel();
if ($panel?->hasTenancy()) {
$query->withoutGlobalScope($panel->getTenancyScopeName());
}
}
$user = auth()->user();
if (! $user instanceof User) {
return $query->whereRaw('1 = 0');
}
/** @var WorkspaceContext $context */
$context = app(WorkspaceContext::class);
$workspace = $context->currentWorkspace();
if (! $workspace instanceof Workspace) {
return $query->whereRaw('1 = 0');
}
if (! $context->isMember($user, $workspace)) {
return $query->whereRaw('1 = 0');
}
return $query->whereBelongsTo($workspace, static::$globalSearchWorkspaceRelationship);
}
}