### Export Data with Custom Mapping and Headings Source: https://context7.com/spartnernl/laravel-excel/llms.txt Enables custom data transformation and addition of column headers to Excel exports. This example shows how to format specific user attributes and define headers using the `WithMapping` and `WithHeadings` concerns, alongside `FromCollection` and `Exportable`. ```php id, $user->name, $user->email, $user->created_at->format('Y-m-d'), ]; } public function headings(): array { return [ 'ID', 'Name', 'Email', 'Registration Date', ]; } } // Usage return (new UsersExport)->download('users.xlsx'); ``` -------------------------------- ### Export Data from Database Query with FromQuery Source: https://context7.com/spartnernl/laravel-excel/llms.txt Facilitates efficient data export directly from database queries, utilizing automatic chunking to optimize memory usage for large datasets. This example uses the `FromQuery` concern along with `Exportable` to export orders based on a specific year and status. ```php year = $year; } public function query() { return Order::query() ->whereYear('created_at', $this->year) ->where('status', 'completed') ->with('customer', 'items'); } } // Controller usage use App\Exports\OrdersExport; // Export orders from 2024 return (new OrdersExport(2024))->download('orders-2024.xlsx'); // Queue large export (new OrdersExport(2024))->queue('exports/orders-2024.xlsx', 'local'); ``` -------------------------------- ### Quick Excel Operations with Facade Source: https://context7.com/spartnernl/laravel-excel/llms.txt Provides static methods on the Excel facade for simplified import and export operations without requiring dedicated classes. This is useful for straightforward tasks like exporting arrays to files or importing data directly into arrays. It supports various formats like XLSX and CSV and allows for custom headers. ```php 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'] ); // Export to CSV instead of XLSX return Excel::download( new \App\Exports\UsersExport, 'users.csv', \Maatwebsite\Excel\Excel::CSV ); ``` -------------------------------- ### Import Excel with Event Listeners Source: https://context7.com/spartnernl/laravel-excel/llms.txt Enables hooking into the Excel import lifecycle using the WithEvents concern. This allows for custom processing, validation, or logging at various stages like before/after import and before/after sheet processing. It requires the MaatwebsiteExcel package and integrates with Laravel's logging capabilities. The import process can be monitored and controlled. ```php importedCount++; return new Transaction([ 'transaction_id' => $row[0], 'amount' => $row[1], 'date' => $row[2], 'description' => $row[3], ]); } public function registerEvents(): array { return [ BeforeImport::class => function(BeforeImport $event) { Log::info('Starting import', ['file' => $event->reader->getPhpSpreadsheetReader()->getLoadedSheetByIndex(0)->getTitle()]); }, BeforeSheet::class => function(BeforeSheet $event) { Log::info('Processing sheet: ' . $event->sheet->getTitle()); }, AfterSheet::class => function(AfterSheet $event) { Log::info('Completed sheet', ['rows' => $event->sheet->getHighestRow()]); }, AfterImport::class => function(AfterImport $event) { Log::info('Import completed', ['total_imported' => $this->importedCount]); }, ]; } } // Usage Excel::import(new TransactionsImport, 'transactions.xlsx'); ``` -------------------------------- ### Export Data from Collections using Exportable Trait Source: https://context7.com/spartnernl/laravel-excel/llms.txt Demonstrates how to export data from Eloquent collections to an Excel file using the `Exportable` trait. Supports direct download, storing to disk, queuing for background processing, and retrieving raw file content. Requires the `FromCollection` concern. ```php download('users.xlsx'); // Store to disk (new UsersExport)->store('exports/users.xlsx', 's3'); // Queue export for background processing (new UsersExport)->queue('exports/users.xlsx', 's3'); // Get raw file contents $rawContent = (new UsersExport)->raw(\Maatwebsite\Excel\Excel::XLSX); ``` -------------------------------- ### Implement Queued Export with ShouldQueue in Laravel Excel Source: https://context7.com/spartnernl/laravel-excel/llms.txt This PHP code demonstrates how to implement the `ShouldQueue` interface for background processing of large Excel exports. It uses `FromQuery`, `WithMapping`, and `Exportable` concerns to define the data source, mapping logic, and export behavior. The `query` method fetches data based on date ranges, and the `map` method structures the output. The controller shows how to instantiate and dispatch the export job. ```php startDate = $startDate; $this->endDate = $endDate; } public function query() { return Order::query() ->whereBetween('created_at', [$this->startDate, $this->endDate]) ->with('customer', 'items'); } public function map($order): array { return [ $order->id, $order->customer->name, $order->total, $order->status, $order->created_at->format('Y-m-d H:i:s'), ]; } } // Controller use App\Exports\LargeOrdersExport; use Illuminate\Http\Request; public function export(Request $request) { $export = new LargeOrdersExport( $request->input('start_date'), $request->input('end_date') ); // Store method automatically dispatches to queue $export->store('exports/orders-' . now()->format('Y-m-d') . '.xlsx', 'local'); return response()->json([ 'message' => 'Export queued successfully' ]); } ``` -------------------------------- ### Performance-Optimized Excel Import with Chunk Reading and Batch Inserts in PHP Source: https://context7.com/spartnernl/laravel-excel/llms.txt This import strategy combines `WithChunkReading` and `WithBatchInserts` for memory-efficient processing of large Excel files and optimized database inserts. It's suitable for large datasets and can be queued for background processing. ```php $row['name'], 'email' => $row['email'], 'phone' => $row['phone'], 'address' => $row['address'], 'city' => $row['city'], 'country' => $row['country'], ]); } public function chunkSize(): int { return 1000; } public function batchSize(): int { return 500; } } // Usage - automatically queued due to ShouldQueue // use App\Imports\CustomersImport; // Excel::import(new CustomersImport, 'customers.xlsx'); // Processes in background: reads 1000 rows at a time, inserts 500 records per batch ``` -------------------------------- ### Import Excel to Eloquent Models using ToModel in PHP Source: https://context7.com/spartnernl/laravel-excel/llms.txt The `ToModel` concern maps Excel rows to Eloquent model instances for database imports. It requires an Eloquent model and can be combined with `WithHeadingRow` for easier column mapping. The input is an Excel file, and the output is populated Eloquent models. ```php $row['name'], 'sku' => $row['sku'], 'price' => $row['price'], 'stock' => $row['stock'], 'category' => $row['category'], ]); } } // Controller usage // use App\Imports\ProductsImport; // use Maatwebsite\Excel\Facades\Excel; // Direct import // Excel::import(new ProductsImport, 'products.xlsx'); // Import from request // Excel::import(new ProductsImport, request()->file('file')); // Import from storage disk // Excel::import(new ProductsImport, 'imports/products.xlsx', 's3'); // Queue import for background processing // Excel::queueImport(new ProductsImport, 'large-products.xlsx'); ``` -------------------------------- ### Export Blade View to Excel using FromView in PHP Source: https://context7.com/spartnernl/laravel-excel/llms.txt The `FromView` concern exports HTML tables from Blade views to Excel. It requires a Blade view and optionally accepts styling and structure preservation. The output is an Excel file. ```php invoice = $invoice; } public function view(): View { return view('exports.invoice', [ 'invoice' => $this->invoice ]); } } // Blade view (resources/views/exports/invoice.blade.php) // // // // // // // // // // // @foreach($invoice->items as $item) // // // // // // // @endforeach // //
ItemQuantityPriceTotal
{{ $item->name }}{{ $item->quantity }}${{ number_format($item->price, 2) }}${{ number_format($item->total, 2) }}
// Usage // return (new InvoiceExport($invoice))->download('invoice-' . $invoice->id . '.xlsx'); ``` -------------------------------- ### Import Excel to Laravel Collection Source: https://context7.com/spartnernl/laravel-excel/llms.txt Imports Excel data into a Laravel collection using the ToCollection concern. This allows for flexible data manipulation without direct database interaction. It requires the MaatwebsiteExcel package and can be used with WithHeadingRow to access columns by name. The output is a collection of rows that can be processed. ```php results['total'] = $rows->count(); $this->results['average_price'] = $rows->avg('price'); $this->results['total_revenue'] = $rows->sum('revenue'); $this->results['top_products'] = $rows->sortByDesc('sales') ->take(10) ->pluck('product_name', 'sales'); } public function getResults() { return $this->results; } } // Usage $import = new DataAnalysisImport; Excel::import($import, 'sales-data.xlsx'); $analysis = $import->getResults(); // Or use the toCollection method directly $collection = Excel::toCollection(new DataAnalysisImport, 'data.xlsx'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.