FilamentF
Filament12mo ago
n4tek

Optimizing Queries in FileUpload – How to Avoid Duplicate Calls?

Hey! I have a problem that’s really bothering me – in the FileUpload component, I have two queries: $record->attachments()->get()->pluck(value: 'file_path')->toArray(). I’m trying to figure this out and optimize it, but I’m stuck and running out of ideas.

My resource has access to a relational table where attachments are stored. I’m only interested in the ones linked to this specific record. The current form of this code annoys me because I know it can be done better and more efficiently. I really want to avoid leaving it like this, but for now, I don’t have a solution. Maybe someone has an idea on how to improve it?

private static function getAttachmentsFormComponent(): FileUpload
    {
        /** @var string $disk */
        $disk = config(key: 'filesystems.default');

        return FileUpload::make(name: 'attachments')
            ->disk(name: $disk)
            ->directory(directory: 'attachments')
            ->hiddenLabel()
            ->panelLayout(layout: 'grid')
            ->multiple()
            ->openable()
            ->formatStateUsing(callback: fn (Attachable $record): array => $record->attachments()->get()->pluck(value: 'file_path')->toArray() ?? [])
            ->dehydrated(condition: false)
            ->saveRelationshipsUsing(callback: static function (Attachable $record, array $state): void {
                $existingAttachments = $record->attachments()->pluck('file_path')->toArray();

                $attachmentsToDelete = array_diff($existingAttachments, $state);
                $attachmentsToAdd = array_diff($state, $existingAttachments);

                dd($attachmentsToDelete, $attachmentsToAdd);
            });
    }
Was this page helpful?