FilamentF
Filament10mo ago
razor

How to add a dropdown and access the selected item in base query

I am using seperate schemas in Postgres with tenancyforlaravel.
I want a dropdown to select the tenant, then I can view the table/create/edit etc...

I want to switch to tenant db connection before query basically.

So how to make a dropdown and then access the current tenant in
getEloquentQuery
.

This is working rn:
public static function getEloquentQuery(): Builder
{
    $tenant = Tenant::first();
    tenancy()->initialize($tenant);

    return parent::getEloquentQuery();
}
Solution
I fixed it. Forgot to give error message and code.
I override route function in every page like List etc, just add custom middleware that reads tenant param.

public static function route(string $path): PageRegistration
    {
        return new PageRegistration(
            page: static::class,
            route: fn(Panel $panel): Route => RouteFacade::get($path, static::class)
                ->middleware(static::getRouteMiddleware($panel))
                ->middleware(InitializeTenancyBySubdomain::class)
                ->withoutMiddleware(static::getWithoutRouteMiddleware($panel)),
        );
    }

InitializeTenancyBySubdomain.php
<?php

namespace App\Http\Middleware;

use App\Models\Tenant;
use Closure;
use Illuminate\Http\Request;

class InitializeTenancyBySubdomain
{
    public function handle(Request $request, Closure $next): mixed
    {
        $route = $request->route();
        $record = $route->parameter('tenant');

        if ($record && $tenant = Tenant::findOrFail($record)) {
            tenancy()->initialize($tenant);
        }

        return $next($request);
    }
}

Example only for index
public static function getPages(): array
    {
        return [
            'index' => Pages\ListUsers::route('/{tenant?}'),
            'create' => Pages\CreateUser::route('/create'),
            'edit' => Pages\EditUser::route('/{record}/edit'),
        ];
    }
Was this page helpful?