|
| 1 | +# Exports |
| 2 | + |
| 3 | +Exporting data from the table can be really useful to quickly get all records in a spreadsheet. Creating an export functionality is very simple using [actions](/usage/actions). |
| 4 | + |
| 5 | +The example below makes use of [maatwebsite/excel](https://laravel-excel.com/). It is not required to use this package, as you can use anything you want. If you are planning to use `maatwebsite/excel`, please follow the installation instructions before continuing. |
| 6 | + |
| 7 | +## Example |
| 8 | + |
| 9 | +Start by adding an action to your table. This example will make use of a [standalone](/usage/actions#standalone) action. By doing so, all records that are available in the table will be included in the export while respecting all filters and sortings. |
| 10 | + |
| 11 | +```php |
| 12 | +protected function actions(): array |
| 13 | +{ |
| 14 | + return [ |
| 15 | + Action::make(__('Export All'), 'export_all', function (): mixed { |
| 16 | + $collection = $this->appliedQuery()->get(); |
| 17 | + |
| 18 | + return Excel::download( |
| 19 | + new BlogExport($collection), 'blogs.xlsx', |
| 20 | + ); |
| 21 | + })->standalone(), |
| 22 | + ]; |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +You can also use a regular action, only exporting records that have been selected. |
| 27 | + |
| 28 | +```php |
| 29 | +protected function actions(): array |
| 30 | +{ |
| 31 | + return [ |
| 32 | + Action::make(__('Export'), 'export', function (Enumerable $models): mixed { |
| 33 | + return Excel::download( |
| 34 | + new BlogExport($models), 'blogs.xlsx', |
| 35 | + ); |
| 36 | + }), |
| 37 | + ]; |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +An example of the `BlogExport` could look like the following. Note that any formatting can be applied in this class. |
| 42 | + |
| 43 | +```php |
| 44 | +<?php |
| 45 | + |
| 46 | +namespace App\Exports; |
| 47 | + |
| 48 | +use Illuminate\Support\Collection; |
| 49 | +use Maatwebsite\Excel\Concerns\FromCollection; |
| 50 | + |
| 51 | +class BlogExport implements FromCollection |
| 52 | +{ |
| 53 | + public function __construct( |
| 54 | + protected Collection $collection |
| 55 | + ) { |
| 56 | + } |
| 57 | + |
| 58 | + public function collection() |
| 59 | + { |
| 60 | + return $this->collection; |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
0 commit comments