FilamentF
Filament13mo ago
Prodex

How to access attributes of a selected record, without duplicate queries?

Hi, I want to display additional information of the selected company using Placeholders. But each time I use Company::find($get('company_id')) an additonal query will be fired. How can I prevent this?

                        Forms\Components\Repeater::make('excursionsCompanies')
                            ->label(__('excursion.excursionsCompanies'))
                            ->addActionLabel(__('excursion.add_company'))
                            ->relationship()
                            ->itemLabel(fn (array $state): ?string => Company::find($state['company_id'])?->name)
                            ->orderColumn('sort')
                            ->schema([
Forms\Components\Select::make('company_id')
                                    ->label(__('company.singular'))
                                    ->live()
                                    ->searchable()
                                    ->relationship('company', 'name')
                                    ->required(),

                                Forms\Components\Placeholder::make('company_address')
                                    ->label(__('company.address'))
                                    ->hidden(fn (Get $get) => ! $get('company_id'))
                                    ->content(fn (Get $get) =>     Company::find($get('company_id'))?->fullAddress),
];

In the example above, 2 duplicate queries are created.

Thank you!
Solution
->content(fn (Get $get) => static::getCompany($get('id'))

static function getCompany(int|string $id) {
   return once(fn () => Company::find($get('company_id'))?->fullAddress));
}
Was this page helpful?