tombro
tombro
FFilament
Created by Wayne_Swart on 1/24/2024 in #❓┊help
Use resource record ID in file upload path
I was in a similar position, but went another way. I wanted all files in all resources to be in their respective directories. Files uploaded to model Product, attribute product_gallery for example, needed to be uploaded to storage/app/private/product/{product_id}/product_gallery I created a ModelObserver that obeserves all models. In both the created() and updated() method, I call the same logic, which: 1. gets all model attributes, filters only fields which contain paths or an array of paths 2. check if the files have already been moved, if not move them rename($oldFilePath, $newFilePath); 3. update the attribute in the database with the new path Right now, this works as it should, only problem is that filament doesn't refresh the values after updating (after page refresh all is fine). To overcome this issue, I removed the ModelObserver::update() logic, and let filament handle this:
FileUpload::configureUsing(function (FileUpload $fileUpload) {
return $fileUpload
->downloadable()
->disk('private')
->directory(function (string $model, ?Model $record) use ($fileUpload) {
if (! $record) {
return;
}

$path = Str::of($model)
->replace('App\\Models\\', '')
->replace('\\', '/')
->snake()
->replace('/_', '/')
->replace('_', '-')
->lower()
->append('/'.$record->getKey())
->append('/'.$fileUpload->getName());

return $path;
});
});
FileUpload::configureUsing(function (FileUpload $fileUpload) {
return $fileUpload
->downloadable()
->disk('private')
->directory(function (string $model, ?Model $record) use ($fileUpload) {
if (! $record) {
return;
}

$path = Str::of($model)
->replace('App\\Models\\', '')
->replace('\\', '/')
->snake()
->replace('/_', '/')
->replace('_', '-')
->lower()
->append('/'.$record->getKey())
->append('/'.$fileUpload->getName());

return $path;
});
});
I don't like having similar logic in two places, but in this case, I don't see any other solution
10 replies