{"id":25648580,"url":"https://github.com/stats4sd/laravel-file-util","last_synced_at":"2025-10-29T00:02:05.701Z","repository":{"id":47767320,"uuid":"409577522","full_name":"stats4sd/laravel-file-util","owner":"stats4sd","description":"Enables your Laravel application to import and export excel file, upload and download files in Crud panel. ","archived":false,"fork":false,"pushed_at":"2022-12-12T15:56:28.000Z","size":48,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-01-31T00:47:47.178Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stats4sd.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null},"funding":{"github":"stats4sd"}},"created_at":"2021-09-23T12:14:16.000Z","updated_at":"2022-11-08T08:54:35.000Z","dependencies_parsed_at":"2023-01-27T21:40:20.985Z","dependency_job_id":null,"html_url":"https://github.com/stats4sd/laravel-file-util","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":"spatie/package-skeleton-laravel","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stats4sd%2Flaravel-file-util","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stats4sd%2Flaravel-file-util/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stats4sd%2Flaravel-file-util/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stats4sd%2Flaravel-file-util/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stats4sd","download_url":"https://codeload.github.com/stats4sd/laravel-file-util/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240317440,"owners_count":19782390,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-02-23T13:15:29.354Z","updated_at":"2025-10-29T00:02:00.682Z","avatar_url":"https://github.com/stats4sd.png","language":"PHP","funding_links":["https://github.com/sponsors/stats4sd"],"categories":[],"sub_categories":[],"readme":"# Laravel File Utility Package\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/stats4sd/fileutil.svg?style=flat-square)](https://packagist.org/packages/stats4sd/fileutil)\n[![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/stats4sd/fileutil/run-tests?label=tests)](https://github.com/stats4sd/fileutil/actions?query=workflow%3Arun-tests+branch%3Amain)\n[![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/stats4sd/fileutil/Check%20\u0026%20fix%20styling?label=code%20style)](https://github.com/stats4sd/fileutil/actions?query=workflow%3A\"Check+%26+fix+styling\"+branch%3Amain)\n[![Total Downloads](https://img.shields.io/packagist/dt/stats4sd/fileutil.svg?style=flat-square)](https://packagist.org/packages/stats4sd/fileutil)\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require stats4sd/laravel-file-util\n```\n## Usage\n\n#### Pre-requisite:\n\nThe package has 3 main features, and you can use one or all of them in your project:\n\n- A trait `HasUploadFields`: this is based heavily on the trait shipped with Laravel Backpack, but customised slightly to our needs. \n  - To use the trait, you need no other dependencies.\n- 2 Operation classes, to be used with Laravel Backpack.\n  - To use these operations, you should install the following extra dependencies:\n    - `composer require backpack/crud`\n    - `composer require maatwebsite/excel`\n\n## 1. Exporting Data through a Laravel Backpack Crud panel\n\nBoth import and export operations use and require the [Laravel Excel](https://docs.laravel-excel.com/3.1) package. \n\nThe ExportOperation lets you link an ModelExport class built with Laravel Excel to your Crud panel.\n\nHow to add an Excel Export:\n\n1. Build your ModelExport class as described [here](https://docs.laravel-excel.com/3.1/exports/)\n - To test this operation class, start with the most basic version of an export (e.g. implement FromCollection and just get some items from your CRUD's model. You can always add things later to customise your export.\n\n```php\n\u003c?php\n\nnamespace App\\Exports;\n\nuse App\\Models\\Tag;\nuse Maatwebsite\\Excel\\Concerns\\WithTitle;\nuse Maatwebsite\\Excel\\Concerns\\WithHeadings;\nuse Maatwebsite\\Excel\\Concerns\\FromCollection;\n\nclass TagsExport implements FromCollection, WithTitle, WithHeadings\n{\n    /**\n    * @return \\Illuminate\\Support\\Collection\n    */\n    public function collection()\n    {\n        return Tag::select(\n            'id',\n            'name',\n            'slug',\n            'files',\n            'created_at',\n            'updated_at',\n        )-\u003eget();\n    }\n\n    /**\n    * @return string\n    */\n    public function title(): string\n    {\n        return 'Tag';\n    }\n\n    public function headings(): array\n    {\n        return [\n            'id',\n            'name',\n            'slug',\n            'files',\n            'created_at',\n            'updated_at',\n        ];\n    }\n}\n```\n\n2. Use your ModelExport class in your CrudController: `use App\\Exports\\TagsExport;` \n\n3. Use the ExportOperation in your CrudController: `use \\Stats4sd\\FileUtil\\Http\\Controllers\\Operations\\ExportOperation;` \n\n4. Add the following in your CrudController: \n`use ExportOperation;` \n\n5. Add the following to your CrudController's setup() method:\n`CRUD::set('export.exporter', YourModelExport::class);` (replace with the actual name of your ModelExport class)\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers\\Admin;\n\nuse App\\Exports\\TagsExport;\nuse \\Stats4sd\\FileUtil\\Http\\Controllers\\Operations\\ExportOperation;\nuse Backpack\\CRUD\\app\\Http\\Controllers\\CrudController;\nuse Backpack\\CRUD\\app\\Library\\CrudPanel\\CrudPanelFacade as CRUD;\n\n/**\n * Class TagCrudController\n * @package App\\Http\\Controllers\\Admin\n * @property-read \\Backpack\\CRUD\\app\\Library\\CrudPanel\\CrudPanel $crud\n */\nclass TagCrudController extends CrudController\n{\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\ListOperation;\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\CreateOperation;\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\UpdateOperation;\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\DeleteOperation;\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\ShowOperation;\n    use ExportOperation;\n\n    /**\n     * Configure the CrudPanel object. Apply settings to all operations.\n     * \n     * @return void\n     */\n    public function setup()\n    {\n        CRUD::setModel(\\App\\Models\\Tag::class);\n        CRUD::setRoute(config('backpack.base.route_prefix') . '/tag');\n        CRUD::setEntityNameStrings('tag', 'tags');\n        CRUD::set('export.exporter', TagsExport::class);\n    }\n\n    /**\n     * Define what happens when the List operation is loaded.\n     * \n     * @see  https://backpackforlaravel.com/docs/crud-operation-list-entries\n     * @return void\n     */\n    protected function setupListOperation()\n    {\n        CRUD::setFromDb(); // columns        \n    }\n\n    /**\n     * Define what happens when the Create operation is loaded.\n     * \n     * @see https://backpackforlaravel.com/docs/crud-operation-create\n     * @return void\n     */\n    protected function setupCreateOperation()\n    {\n        CRUD::setFromDb(); // fields\n    }\n\n    /**\n     * Define what happens when the Update operation is loaded.\n     * \n     * @see https://backpackforlaravel.com/docs/crud-operation-update\n     * @return void\n     */\n    protected function setupUpdateOperation()\n    {\n        $this-\u003esetupCreateOperation();\n    }\n}\n\n```\n\nThat's it! The operation adds an \"Export\" button to the 'top' stack in List view. Click the button to download the File generated from your ModelExport class.\n\n**Notes**:\n - The default file name is the Crud entity_plural_name, with a date-time string appended to the end.\n - The default format is .xlsx\n - To override, add an export() method to your crud controller. \n\nEverything about the exported file is defined by the ModelExport class. You can customise it using any of the features of [Laravel Excel](https://docs.laravel-excel.com/3.1) as you would if you were using the package anywhere else in Laravel. All this Operation does is make it easier to quickly link an ModelExport class to a Crud panel. \n\n## 2. Importing Data through a Laravel Backpack Crud panel\nThe ImportOperation lets you link an ModelImport class built with Laravel Excel to your Crud panel.\n\nHow to add:\n\n1. Build your ModelImport class as described [here](https://docs.laravel-excel.com/3.1/imports/)\n\n```php\n\u003c?php\n\nnamespace App\\Imports;\n\nuse App\\Models\\Tag;\nuse Maatwebsite\\Excel\\Concerns\\ToModel;\nuse Maatwebsite\\Excel\\Concerns\\WithHeadingRow;\n\nclass TagsImport implements ToModel, WithHeadingRow\n{\n    /**\n     * @param array $row\n     *\n     * @return Tags|null\n     */\n    public function model(array $row)\n    {\n        return new Tag([\n           'name'       =\u003e $row['name'],\n           'slug'       =\u003e $row['slug'],\n           'files'      =\u003e $row['files'],\n        ]);\n    }\n}\n```\n\n2. Build your ImportRequest class as below\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Requests;\n\nuse App\\Http\\Requests\\Request;\nuse Illuminate\\Foundation\\Http\\FormRequest;\n\nclass ImportRequest extends FormRequest\n{\n    /**\n     * Determine if the user is authorized to make this request.\n     *\n     * @return bool\n     */\n    public function authorize()\n    {\n        // only allow updates if the user is logged in\n        return backpack_auth()-\u003echeck();\n    }\n\n    /**\n     * Get the validation rules that apply to the request.\n     *\n     * @return array\n     */\n    public function rules()\n    {\n        return [\n            'importFile' =\u003e 'required|file|mimes:xls,xlsx|max:24000',\n        ];\n    }\n\n    /**\n     * Get the validation attributes that apply to the request.\n     *\n     * @return array\n     */\n    public function attributes()\n    {\n        return [\n            //\n        ];\n    }\n\n    /**\n     * Get the validation messages that apply to the request.\n     *\n     * @return array\n     */\n    public function messages()\n    {\n        return [\n            //\n        ];\n    }\n}\n```\n\n3. Use your ModelImport class in your CrudController: `use App\\Imports\\TagsImport;` \n\n4. Use the ImportOperation in your CrudController: `use \\Stats4sd\\FileUtil\\Http\\Controllers\\Operations\\ImportOperation;` \n\n5. Add the following in your CrudController: \n`use ImportOperation;` \n\n6. Add the following to your CrudController's setup() method:\n`CRUD::set('import.importer', YourModelImport::class);` (replace with the actual name of your ModelImport class)\n\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers\\Admin;\n\nuse App\\Imports\\TagsImport;\nuse \\Stats4sd\\FileUtil\\Http\\Controllers\\Operations\\ImportOperation;\nuse Backpack\\CRUD\\app\\Http\\Controllers\\CrudController;\nuse Backpack\\CRUD\\app\\Library\\CrudPanel\\CrudPanelFacade as CRUD;\n\n/**\n * Class TagCrudController\n * @package App\\Http\\Controllers\\Admin\n * @property-read \\Backpack\\CRUD\\app\\Library\\CrudPanel\\CrudPanel $crud\n */\nclass TagCrudController extends CrudController\n{\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\ListOperation;\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\CreateOperation;\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\UpdateOperation;\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\DeleteOperation;\n    use \\Backpack\\CRUD\\app\\Http\\Controllers\\Operations\\ShowOperation;\n    use ImportOperation;\n\n    /**\n     * Configure the CrudPanel object. Apply settings to all operations.\n     * \n     * @return void\n     */\n    public function setup()\n    {\n        CRUD::setModel(\\App\\Models\\Tag::class);\n        CRUD::setRoute(config('backpack.base.route_prefix') . '/tag');\n        CRUD::setEntityNameStrings('tag', 'tags');\n        CRUD::set('import.importer', TagsImport::class);\n    }\n\n    /**\n     * Define what happens when the List operation is loaded.\n     * \n     * @see  https://backpackforlaravel.com/docs/crud-operation-list-entries\n     * @return void\n     */\n    protected function setupListOperation()\n    {\n        CRUD::setFromDb(); // columns        \n    }\n\n    /**\n     * Define what happens when the Create operation is loaded.\n     * \n     * @see https://backpackforlaravel.com/docs/crud-operation-create\n     * @return void\n     */\n    protected function setupCreateOperation()\n    {\n        CRUD::setFromDb(); // fields\n    }\n\n    /**\n     * Define what happens when the Update operation is loaded.\n     * \n     * @see https://backpackforlaravel.com/docs/crud-operation-update\n     * @return void\n     */\n    protected function setupUpdateOperation()\n    {\n        $this-\u003esetupCreateOperation();\n    }\n}\n```\n\nThat's it! The operation adds an \"Import\" button to the 'top' stack in List view. Click this button to be taken to the Import View. This view contains a basic form with a file upload input and a submit button. Add an Excel file, submit, and the file will be processed by your ModelImport class.\n\n\n**Notes**:\n - It's recommended to add validation to your importer. (See documentation page on [validating rows](https://docs.laravel-excel.com/3.1/imports/validation.html))\n - The import form has support for displaying errors returned from validation. If you use batch imports, you will see errors from the entire batch of rows at once, labeled with the correct row number. This is useful for seeing all errors at once in an Excel file, instead of going row-by-row and having to try importing the same file multiple times until it works with no validation errors. \n\n**TO DO: add examples of validation with both ToModel / BatchInserts AND ToCollection concerns**\n\n## 3. File Upload + File Download Operations\n\n1. Use FileController class in your routes\\web.php: `use \\Stats4sd\\FileUtil\\Http\\Controllers\\FileController;`\n\n2. Add below section in your routes\\web.php\n\n```\nRoute::group([\n    'middleware' =\u003e ['web']\n], function () {\n    Route::get('image/{path}', [FileController::class, 'getImage'])-\u003ewhere('path', '.*')-\u003ename('image.get');\n    Route::get('download/{path}/{disk?}', [FileController::class, 'download'])-\u003ewhere('path', '.*')-\u003ename('file.download');\n});\n```\n\n3. In config\\filesystem.php, add a line to \"disks\" \\ \"local\" section\n`'url' =\u003e env('APP_URL').'/download/',`\n\n4. Use HasUploadFields class in your Model class: `use \\Stats4sd\\FileUtil\\Models\\Traits\\HasUploadFields;`\n\n5. Use trait HasUploadFields class in your Model class: `use CrudTrait, HasUploadFields;`\n\n6. Add below function to your Model class, it will save uploaded files into folder \"storage\\app\\site\". File name will be stored in Model class column \"files\"\n\n```\n    public function setFilesAttribute($value)\n    {\n        $attribute_name = \"files\";\n        $disk = \"local\";\n        $destination_path = \"site\";\n\n        $this-\u003euploadMultipleFilesWithNames($value, $attribute_name, $disk, $destination_path);\n    }\n```\n\n7. Add the following to your CrudController's setupCreateOperation() method:\n`CRUD::field('files')-\u003etype('upload_multiple')-\u003edisk('local')-\u003eupload(true)-\u003elabel('Files or charts for the site')-\u003ehint('If you have charts or other files, please upload them here');`\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.\n\n## Security Vulnerabilities\n\nPlease review [our security policy](../../security/policy) on how to report security vulnerabilities.\n\n## Credits\n\n- [Dan Tang](https://github.com/stats4sd)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstats4sd%2Flaravel-file-util","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstats4sd%2Flaravel-file-util","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstats4sd%2Flaravel-file-util/lists"}