FilamentF
Filament2y ago
ruff

FileUpload store path instead of filename

Hello everyoone. Just moved to Filament from previous legacy admin panel. I really need FileUpload to store relative path instead of just a filename for compatibility reasons. Is it possible to achieve with hooks like before and after hydration?
Solution
I was able to achieve this by extending FileUpload class
namespace App\Forms\Components;

class FileUpload extends BaseFileUpload
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->afterStateHydrated(static function (BaseFileUpload $component, string | array | null $state): void {
            if (blank($state)) {
                $component->state([]);

                return;
            }

            $shouldFetchFileInformation = $component->shouldFetchFileInformation();

            $files = collect(Arr::wrap($state))
                ->map(static fn (string $file): string => str_replace("uploads/", "", $file))
                ->filter(static function (string $file) use ($component, $shouldFetchFileInformation): bool {
                    if (blank($file)) {
                        return false;
                    }

                    if (! $shouldFetchFileInformation) {
                        return true;
                    }

                    try {
                        return $component->getDisk()->exists($file);
                    } catch (UnableToCheckFileExistence $exception) {
                        return false;
                    }
                })
                ->mapWithKeys(static fn (string $file): array => [((string) Str::uuid()) => $file])
                ->all();

            $component->state($files);
        });

        $this->dehydrateStateUsing(static function (BaseFileUpload $component, ?array $state): string | array | null | TemporaryUploadedFile {
            $files = collect(array_values($state ?? []))->map(static fn (string $file): string => "uploads/".($file));
            
            if ($component->isMultiple()) {
                return $files;
            }

            return $files[0] ?? null;
        });
    }
}
Was this page helpful?