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),
];
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')) ```php static function getCompany(int|string $id) { return once(fn () => Company::find($get('company_id'))?->fullAddress));...
Jump to solution
4 Replies
Dennis Koch
Dennis Koch2w ago
You can't access the record directly. I usually add a function to cache the response for a short period.
Prodex
ProdexOP2w ago
do you have an example?
Solution
Dennis Koch
Dennis Koch2w ago
->content(fn (Get $get) => static::getCompany($get('id'))
static function getCompany(int|string $id) {
return once(fn () => Company::find($get('company_id'))?->fullAddress));
}
static function getCompany(int|string $id) {
return once(fn () => Company::find($get('company_id'))?->fullAddress));
}
Prodex
ProdexOP2w ago
oh, cool "hack". Worked perfectly.
Want results from more Discord servers?
Add your server