### Install Laravel Nova Excel Package (Composer) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/nova/1.x/exports/README.md Requires the maatwebsite/laravel-nova-excel package using Composer. This command adds the package dependency to the project's composer.json and downloads it along with Laravel Excel. ```Shell composer require maatwebsite/laravel-nova-excel ``` -------------------------------- ### Defining Laravel Route for Excel Export Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/README.md This Laravel route definition creates a GET endpoint at `/users/export/`. When accessed, it will call the `export` method of the `UsersController` class, initiating the Excel file download. ```PHP Route::get('users/export/', [UsersController::class, 'export']); ``` -------------------------------- ### Install Laravel Excel with Composer (Latest Compatible) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/getting-started/installation.md Installs the latest compatible version of the Maatwebsite Excel package using Composer. This is the recommended approach if the version-specific command fails or you want the most recent features compatible with your environment. ```bash composer require maatwebsite/excel ``` -------------------------------- ### Install Laravel Nova Excel Package via Composer (Bash) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/nova/1.x/getting-started/installation.md This command uses Composer to require the `maatwebsite/laravel-nova-excel` package along with a specific version of `psr/simple-cache` to satisfy dependencies, particularly for Laravel 9 compatibility. ```bash composer require psr/simple-cache:^2.0 maatwebsite/laravel-nova-excel ``` -------------------------------- ### Installing Maatwebsite Excel Package via Composer (Shell) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/getting-started/installation.md This command uses Composer to download and install the `maatwebsite/excel` package along with its required dependencies, including PhpSpreadsheet, into your Laravel project. It should be executed in the root directory of your Laravel application. ```Shell composer require maatwebsite/excel ``` -------------------------------- ### Triggering Laravel Excel Download via Route (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/exports/README.md Defines a GET route `/users/export` that uses the `Excel::download` facade method to initiate a file download. It takes an instance of the `UsersExport` class and the desired filename (`users.xlsx`) as arguments, sending the generated spreadsheet directly to the browser. ```php Route::get('users/export', function() { return Excel::download(new UsersExport, 'users.xlsx'); }); ``` -------------------------------- ### Install Laravel CSV via Composer Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/csv/1.0/getting-started/installation.md Installs the `maatwebsite/laravel-csv` package and its dependencies using Composer. This is the standard method for adding the package to your Laravel project. ```Bash composer require maatwebsite/laravel-csv ``` -------------------------------- ### Triggering Laravel Excel Download from Controller Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/README.md This PHP controller method `export` uses the `Maatwebsite\Excel` facade to trigger a file download. It instantiates the `UsersExport` class and calls the `download` method, specifying the export instance and the desired filename (`users.xlsx`). This method is typically called from a web route. ```PHP [ /* * Package Service Providers... */ Maatwebsite\Excel\ExcelServiceProvider::class, ] ``` -------------------------------- ### Defining Laravel Excel Export Class (FromCollection) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/README.md This PHP class `UsersExport` implements the `FromCollection` concern from `Maatwebsite\Excel`. It defines a `collection` method that returns a collection of all `User` models, which will be used as the data source for the Excel export. ```PHP actingAs($this->givenUser()) ->get('/invoices/queue/xlsx'); Excel::assertQueued('filename.xlsx', 'diskName'); Excel::assertQueued('filename.xlsx', 'diskName', function(InvoicesExport $export) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertQueued('filename.xlsx', function(InvoicesExport $export) { return true; }); // Assert that the export was queued with a specific chain of other jobs. Excel::assertQueuedWithChain([ new NotifyUsers(), ]); } ``` -------------------------------- ### Require Package Laravel 4 Composer Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/getting-started/README.md Specifies the required version of the maatwebsite/excel package for Laravel 4 within the composer.json file's require section. ```Composer "maatwebsite/excel": "~1.3" ``` -------------------------------- ### Publish Laravel Excel Configuration File Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/getting-started/installation.md Run this Artisan command to publish the default configuration file for Laravel Excel, creating config/excel.php where you can customize settings. ```bash php artisan vendor:publish ``` -------------------------------- ### Register Facade Alias Laravel PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/getting-started/README.md Adds a facade alias for the package to the aliases array in the Laravel application configuration file, enabling shorter syntax like 'Excel::load()'. ```PHP 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ``` -------------------------------- ### Add DownloadExcel Action to Nova Resource (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/nova/1.x/exports/README.md Adds the Maatwebsite\LaravelNovaExcel\Actions\DownloadExcel action to the actions() method of a Nova resource class (e.g., App\Nova\User). This makes the 'Download Excel' action available in the Nova admin panel for this resource. ```PHP [ /* * Package Service Providers... */ Maatwebsite\LaravelCsv\LaravelCsvServiceProvider::class, ] ``` -------------------------------- ### Implementing WithStartRow Concern for Imports in PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/start-row.md This snippet demonstrates how to implement the `WithStartRow` concern in an import class. By implementing the `startRow()` method and returning `2`, the import process will skip the first row (row 1), effectively starting data processing from the second row. ```PHP namespace App\Imports; use App\User; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithStartRow; class UsersImport implements ToModel, WithStartRow { public function model(array $row) { return new User([ 'name' => $row[0], ]); } public function startRow(): int { return 2; } } ``` -------------------------------- ### Creating Laravel Excel Import Class via Artisan Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/README.md Generate a basic import class file using the Laravel Artisan command-line tool, specifying the class name and an optional model to integrate with Eloquent. ```bash php artisan make:import UsersImport --model=User ``` -------------------------------- ### Publish Laravel CSV Configuration Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/csv/1.0/getting-started/installation.md Publishes the default configuration file for the Laravel CSV package to `config/csv.php`. This allows you to customize package settings. ```Bash php artisan vendor:publish --provider="Maatwebsite\LaravelCsv\LaravelCsvServiceProvider" ``` -------------------------------- ### Selecting columns using get method parameter (Laravel Excel) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/import/select.md Demonstrates an alternative way to specify which columns to retrieve by passing an array of column names directly as the first parameter to retrieval methods like `get`. Requires a `$reader` instance. ```PHP $reader->get(array('firstname', 'lastname')); ``` -------------------------------- ### Register Laravel CSV Facade (Manual) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/csv/1.0/getting-started/installation.md Manually registers the `Csv` facade alias pointing to `Maatwebsite\LaravelCsv\Facades\Csv` in the `config/app.php` file. This step is only needed if auto-discovery is disabled. ```PHP 'aliases' => [ ... 'Csv' => Maatwebsite\LaravelCsv\Facades\Csv::class, ] ``` -------------------------------- ### Example Job for Notifying User After Export (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/nova/1.x/exports/customizations.md Provides a basic example of a Laravel job (`NotifyUserOfCompletedExport`) that implements `ShouldQueue` and could be used to notify a user after a queued export is finished. ```php user = $user; } public function handle() { $this->user->notify(...); } } ``` -------------------------------- ### Example Blade View for Excel Export Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/from-view.md Provides an example of a Blade template (`users.blade.php` or similar) structured as an HTML ``. The `FromView` concern processes this table structure, using `` for headers and `` with `` and `
` for data rows, to build the Excel spreadsheet. ```html @foreach($users as $user) @endforeach
Name Email
{{ $user->name }} {{ $user->email }}
``` -------------------------------- ### Manually Registering Maatwebsite Excel Facade (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/getting-started/installation.md This PHP code snippet demonstrates how to manually add the `Excel` facade alias to the `aliases` array within your `config/app.php` file. This allows you to use the `Excel` facade throughout your application without needing the fully qualified class name, and is only required if auto-discovery is off. ```PHP 'aliases' => [ ... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ] ``` -------------------------------- ### Setting Custom Start Cell for Export (Laravel Excel) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/exports/data.md Illustrates how to use the `WithCustomStartCell` concern to specify a custom starting cell for the export data, overriding the default 'A1'. Note that this concern is only supported for `FromCollection` exports. ```php use Maatwebsite\Excel\Concerns\WithCustomStartCell; class UsersExport implements FromCollection, WithCustomStartCell { public function startCell(): string { return 'B2'; } } ``` -------------------------------- ### Basic Column Definition Syntax Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/exports/columns.md This is a syntax example showing the basic structure of `Column::make()`. It takes a required title for the column header and an optional attribute name from the model to map the data. ```php Column::make('{Title}', '{attribute}'); ``` -------------------------------- ### Using Laravel Excel Import Class in Controller Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/README.md Illustrates how to call the Excel::import facade method within a controller method, passing an instance of the import class and the file path to initiate the import process. ```php use App\Imports\UsersImport; use Maatwebsite\Excel\Facades\Excel; use App\Http\Controllers\Controller; class UsersController extends Controller { public function import() { Excel::import(new UsersImport, 'users.xlsx'); return redirect('/')->with('success', 'All good!'); } } ``` -------------------------------- ### Manually Register Laravel Excel Service Provider Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/getting-started/installation.md Adds the Maatwebsite\Excel\ExcelServiceProvider to the 'providers' array in the Laravel config/app.php file. This step is only necessary if auto-discovery is disabled or not working. ```php 'providers' => [ /* * Package Service Providers... */ Maatwebsite\Excel\ExcelServiceProvider::class, ] ``` -------------------------------- ### Register Laravel Nova Excel Service Providers (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/nova/1.x/getting-started/installation.md This PHP code snippet shows how to manually register the required service providers for the Laravel Excel and Laravel Nova Excel packages in the `config/app.php` file, necessary if auto-discovery is not enabled. ```php 'providers' => [ /* * Package Service Providers... */ Maatwebsite\Excel\ExcelServiceProvider::class, Maatwebsite\LaravelNovaExcel\LaravelNovaExcelServiceProvider::class, ] ``` -------------------------------- ### FromCollection Export with Custom Start Cell - PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/collection.md Shows how to implement the `WithCustomStartCell` concern to specify a starting cell other than the default 'A1' for the exported data. The `startCell` method returns the desired cell string. ```php namespace App\Exports; use App\Invoice; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\WithCustomStartCell; class InvoicesExport implements FromCollection, WithCustomStartCell { public function collection() { return Invoice::all(); } public function startCell(): string { return 'B2'; } } ``` -------------------------------- ### Use Laravel Excel via Constructor Dependency Injection Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/getting-started/installation.md Inject the Maatwebsite\Excel\Excel manager class into your controller or class constructor to utilize its methods, such as 'download', for exporting data. ```php use App\YourExport; use Maatwebsite\Excel\Excel; class YourController { private $excel; public function __construct(Excel $excel) { $this->excel = $excel; } public function export() { return $this->excel->download(new YourExport); } } ``` -------------------------------- ### Example Output for Multiple Row Mapping (CSV) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/csv/1.0/exports/mapping.md Illustrates the expected CSV output format when using the multiple row mapping technique. Each original item (e.g., an invoice) results in multiple rows in the final export file. ```text "#","date" "amount","status" "201901564","2019-07-04" "350","paid" "201901566","2019-07-03" "645","pending" "201901568","2019-07-02" "100","paid" "201901458","2019-07-01" "999","cancelled" ``` -------------------------------- ### Registering Events with WithEvents in PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/extending.md Demonstrates how to register event listeners for the import process by implementing the `WithEvents` concern and returning an array of events and callables in the `registerEvents` method. Shows examples using closures, invokable classes, and array callables. ```php namespace App\Imports; use Maatwebsite\Excel\Concerns\WithEvents; use Maatwebsite\Excel\Events\BeforeImport; use Maatwebsite\Excel\Events\AfterImport; use Maatwebsite\Excel\Events\AfterSheet; use Maatwebsite\Excel\Events\BeforeSheet; class UsersImport implements WithEvents { /** * @return array */ public function registerEvents(): array { return [ // Handle by a closure. BeforeImport::class => function(BeforeImport $event) { $creator = $event->reader->getProperties()->getCreator(); }, // Using a class with an __invoke method. BeforeSheet::class => new BeforeSheetHandler(), // Array callable, refering to a static method. AfterSheet::class => [self::class, 'afterSheet'], ]; } public static function afterSheet(AfterSheet $event) { // } } ``` -------------------------------- ### Manually Register Laravel Excel Facade Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/getting-started/installation.md Similar to the Service Provider, the Excel facade is auto-discovered. If manual registration is needed, add the Facade class alias to the 'aliases' array in your config/app.php file. ```php 'aliases' => [ ... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ] ``` -------------------------------- ### Running Tests with PHPUnit Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/getting-started/contributing.md Describes how to execute the project's test suite using the PHPUnit command-line tool via the vendor bin directory. ```Shell vendor/bin/phpunit ``` -------------------------------- ### Use Laravel Excel via Exporter Interface Injection Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/getting-started/installation.md Inject the Maatwebsite\Excel\Exporter interface instead of the concrete Excel class for better decoupling, allowing you to use the 'download' method via the interface. ```php use App\YourExport; use Maatwebsite\Excel\Exporter; class YourController { private $exporter; public function __construct(Exporter $exporter) { $this->exporter = $exporter; } public function export() { return $this->exporter->download(new YourExport); } } ``` -------------------------------- ### Defining a Chained Job Class in PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/queued.md This is an example of a simple job class that can be chained after a queued import. It implements `ShouldQueue` and includes basic setup for queueing and serialization. ```PHP namespace App\Jobs; use App\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\SerializesModels; class NotifyUserOfCompletedImport implements ShouldQueue { use Queueable, SerializesModels; public $user; public function __construct(User $user) { $this->user = $user; } public function handle() { $this->user->notify(new ImportReady()); } } ``` -------------------------------- ### Defining Laravel Excel Import Class (ToModel) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/README.md Shows the structure of a basic import class implementing the ToModel concern, demonstrating how to map array data from a row to a new Eloquent model instance for database insertion. ```php $row[0], 'email' => $row[1], 'password' => Hash::make($row[2]), ]); } } ``` -------------------------------- ### Manually Register Laravel Excel Facade Alias Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/getting-started/installation.md Adds the 'Excel' facade alias to the 'aliases' array in the Laravel config/app.php file. This step is only necessary if auto-discovery is disabled or not working, allowing you to use the 'Excel' facade directly. ```php 'aliases' => [ ... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ] ``` -------------------------------- ### Selecting columns using select method (Laravel Excel) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/import/select.md Shows how to specify which columns to retrieve from the selected sheet(s) using the `select` method with an array of column names before calling a retrieval method like `get`. Requires a `$reader` instance. ```PHP $reader->select(array('firstname', 'lastname'))->get(); ``` -------------------------------- ### Calling Laravel Excel Import in Controller (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/README.md Demonstrates how to trigger the import process from a controller method. It uses the `Excel` facade's `import` method, passing an instance of the import class and the path to the file being imported. ```php with('success', 'All good!'); } } ``` -------------------------------- ### Downloading Filtered FromQuery Export (Constructor) in Laravel Excel (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/from-query.md Shows how to instantiate the `InvoicesExport` class, passing the filtering parameter (e.g., `2018`) to the constructor. The `download()` method is then called to get the filtered export. ```php return (new InvoicesExport(2018))->download('invoices.xlsx'); ``` -------------------------------- ### Triggering Laravel Excel Export from Controller in PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/README.md Call the export class from a controller method using the Excel facade's download method. This method takes an instance of the export class and the desired filename for the downloaded file. ```PHP use App\Exports\UsersExport; use Maatwebsite\Excel\Facades\Excel; use App\Http\Controllers\Controller; class UsersController extends Controller { public function export() { return Excel::download(new UsersExport, 'users.xlsx'); } } ``` -------------------------------- ### Creating Laravel Excel Export Class via Artisan Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/README.md Use the Artisan command-line tool to quickly generate a new export class for the Laravel Excel package. The --model flag can be used to automatically configure the export to fetch data from a specific Eloquent model. ```Shell php artisan make:export UsersExport --model=User ``` -------------------------------- ### Implementing Laravel Excel ToModel Import (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/README.md Defines an import class that implements the `ToModel` concern. The `model` method is called for each row in the spreadsheet and should return an Eloquent model instance populated with data from the row array. ```php $row[0], 'email' => $row[1], 'password' => Hash::make($row[2]), ]); } } ``` -------------------------------- ### Testing Queued Excel Imports with Fake Facade (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/testing.md Shows how to test queued Laravel Excel imports using the fake facade. It provides examples of asserting that a file was queued for import, including variations with and without a validation callback. ```php /** * @test */ public function user_can_queue_the_users_import() { Excel::fake(); $this->actingAs($this->givenUser()) ->get('/users/queue/xlsx'); Excel::assertQueued('filename.xlsx', 'diskName'); Excel::assertQueued('filename.xlsx', 'diskName', function(UsersImport $import) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertQueued('filename.xlsx', function(UsersImport $import) { return true; }); } ``` -------------------------------- ### Testing Excel Storing with Fake Facade (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/testing.md Shows how to test storing Excel exports using `Excel::fake()`. It simulates a user action that triggers storing and then asserts that the file was stored on a specific disk. Includes examples with and without a content verification callback. Requires the Laravel Excel package and a testing environment. ```php /** * @test */ public function user_can_store_invoices_export() { Excel::fake(); $this->actingAs($this->givenUser()) ->get('/invoices/store/xlsx'); Excel::assertStored('filename.xlsx', 'diskName'); Excel::assertStored('filename.xlsx', 'diskName', function(InvoicesExport $export) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertStored('filename.xlsx', function(InvoicesExport $export) { return true; }); } ``` -------------------------------- ### Example Chained Job for Import Completion Notification in PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/queued.md This is an example of a simple queued job that can be chained after a queued import finishes successfully. It demonstrates how to notify a user that their import is ready. ```php namespace App\Jobs; use App\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\SerializesModels; class NotifyUserOfCompletedImport implements ShouldQueue { use Queueable, SerializesModels; public $user; public function __construct(User $user) { $this->user = $user; } public function handle() { $this->user->notify(new ImportReady()); } } ``` -------------------------------- ### Creating a Basic Export Class (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/csv/1.0/exports/README.md This PHP snippet defines an export class `UsersExport` that implements the `FromCollection` concern from the `Maatwebsite\LaravelCsv` package. The `collection` method is required by the interface and is responsible for fetching the data to be exported, in this case, all users from the database. ```php namespace App\Exports;\n\nuse App\User;\nuse Maatwebsite\LaravelCsv\Concerns\FromCollection;\n\nclass UsersExport implements FromCollection\n{\n public function collection()\n {\n return User::all();\n }\n} ``` -------------------------------- ### Downloading Laravel Excel Export with Constructor (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/architecture/objects.md Demonstrates how to use the `Excel::download` helper function to initiate a file download. It instantiates the `UsersExport` class, passing the year `2019` to its constructor, and specifies the desired filename `users.xlsx`. This shows the practical usage of an export object configured via its constructor. ```PHP Excel::download(new UsersExport(2019), 'users.xlsx'); ``` -------------------------------- ### Registering Global Laravel Excel Event Listener (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/architecture/objects.md Shows how to register a global event listener for the BeforeExport event using the static Writer::listen method. This closure will execute before any export process starts across the application. ```php Writer::listen(BeforeExport::class, function () { // Do something before any export process starts. }); ``` -------------------------------- ### Getting Raw Export Contents Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/exports/exporting.md Use the `Excel::raw()` facade method to get the binary contents of the exported file as a string. This is useful for scenarios like attaching the file to an email or returning it directly in an API response. ```php $contents = Excel::raw(new UsersExport, 'users.xlsx'); ``` -------------------------------- ### Testing Queuing Exports with Laravel Excel Fake Facade (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/testing.md This snippet illustrates how to test that an export was queued as a job using `Excel::fake()`. It provides examples of asserting queuing with the filename and disk, or with an optional callback to inspect the export instance. It also shows how to assert queuing to the default disk. ```php /** * @test */ public function user_can_queue_invoices_export() { Excel::fake(); $this->actingAs($this->givenUser()) ->get('/invoices/queue/xlsx'); Excel::assertQueued('filename.xlsx', 'diskName'); Excel::assertQueued('filename.xlsx', 'diskName', function(InvoicesExport $export) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertQueued('filename.xlsx', function(InvoicesExport $export) { return true; }); } ``` -------------------------------- ### Creating Laravel Excel Import Class via Artisan (Shell) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/README.md Use the Artisan command `make:import` to generate a new import class file in the `app/Imports` directory. The `--model` flag can be used to associate the import with a specific Eloquent model. ```shell php artisan make:import UsersImport --model=User ``` -------------------------------- ### Getting All Imported Results (Laravel Excel, PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/import/results.md Shows how to retrieve all sheets or rows from an imported Excel file using the ->get() or ->all() methods after loading the file. The return type depends on the 'force_sheets_collection' config setting. ```PHP Excel::load('file.xls', function($reader) { })->get(); ``` ```PHP Excel::load('file.xls', function($reader) { // Getting all results $results = $reader->get(); // ->all() is a wrapper for ->get() and will work the same $results = $reader->all(); }); ``` -------------------------------- ### Importing from Default Disk (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/basics.md Demonstrates how to import data from a file located on the default filesystem disk using the Excel::import method. It takes the import class instance and the file path relative to the disk root. ```php Excel::import(new UsersImport, 'users.xlsx'); ``` -------------------------------- ### Injecting ExcelFile and Getting Data in Controller (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/import/injection.md Illustrates injecting a custom ExcelFile class (UserListImport) into a controller method using Laravel's dependency injection. It then calls the get() method on the injected instance to retrieve the processed data from the Excel/CSV file. ```PHP class ExampleController extends Controller { public function importUserList(UserListImport $import) { // get the results $results = $import->get(); } } ``` -------------------------------- ### Testing Queued Imports with Excel Fake Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/testing.md This snippet illustrates how to test queued file imports using the faked Excel facade. It shows the use of `Excel::fake()` followed by `Excel::assertQueued()` to verify that a specific file import was queued. Examples cover asserting by filename and disk, and asserting with a callback function. ```php /** * @test */ public function user_can_queue_the_users_import() { Excel::fake(); $this->actingAs($this->givenUser()) ->get('/users/queue/xlsx'); Excel::assertQueued('filename.xlsx', 'diskName'); Excel::assertQueued('filename.xlsx', 'diskName', function(UsersImport $import) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertQueued('filename.xlsx', function(UsersImport $import) { return true; }); } ``` -------------------------------- ### Forcing Remote Temporary File Resync/Cleanup in Multi-Server Setup in PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/queued.md To prevent local temporary files from accumulating on individual servers in a multi-server setup, set `force_resync_remote` to `true` in `config/excel.php`. This ensures the local temporary file is deleted after each chunk is processed by a worker. ```php 'temporary_files' => [ 'force_resync_remote' => true, ], ``` -------------------------------- ### Downloading FromQuery with Constructor Parameter (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/from-query.md Shows how to download an export where the `FromQuery` class accepts a parameter via its constructor. The parameter is passed when instantiating the export class before calling the `download()` method. ```PHP return (new InvoicesExport(2018))->download('invoices.xlsx'); ``` -------------------------------- ### Defining Export Structure with Blade View (HTML) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/from-view.md Provides an example of a Blade template (`invoices.blade.php`) used by the `FromView` export concern. It defines a standard HTML table structure. The content within the `` tags, including headers and data rows generated by iterating over the `$invoices` variable, will be converted into the Excel spreadsheet content. ```HTML
\n \n \n \n \n \n \n \n @foreach($invoices as $invoice)\n \n \n \n \n @endforeach\n \n
NameEmail
{{ $invoice->name }}{{ $invoice->email }}
``` -------------------------------- ### Downloading Laravel Excel Export Object with Constructor (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/architecture/objects.md Demonstrates how to instantiate the UsersExport class by passing the year to its constructor and then using the Excel::download helper function to initiate the export process, saving the file as 'users.xlsx'. ```php Excel::download(new UsersExport(2019), 'users.xlsx'); ``` -------------------------------- ### Testing File Imports with Excel Fake Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/testing.md This snippet demonstrates how to test file imports by faking the Excel facade. It shows how to use `Excel::fake()` to prevent actual file operations and then use `Excel::assertImported()` to verify that a specific file was intended to be imported. Examples include asserting by filename and disk, and asserting with a callback function. ```php /** * @test */ public function user_can_import_users() { Excel::fake(); $this->actingAs($this->givenUser()) ->get('/users/import/xlsx'); Excel::assertImported('filename.xlsx', 'diskName'); Excel::assertImported('filename.xlsx', 'diskName', function(UsersImport $import) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertImported('filename.xlsx', function(UsersImport $import) { return true; }); } ``` -------------------------------- ### Creating Laravel Excel Export using Artisan (Shell) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/exports/README.md Uses the Laravel Artisan command `make:export` to generate a new export class named `UsersExport`. The `--model=User` flag indicates that the export should be based on the `User` Eloquent model, automatically implementing the `FromCollection` concern and providing a basic `collection()` method. ```shell php artisan make:export UsersExport --model=User ``` -------------------------------- ### Testing Storing Exports with Laravel Excel Fake Facade (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/testing.md This snippet shows how to test that an export was stored to a disk using `Excel::fake()`. It provides examples of asserting storage with just the filename and disk, or with an optional callback to inspect the export instance. It also shows how to assert storage to the default disk. ```php /** * @test */ public function user_can_store_invoices_export() { Excel::fake(); $this->actingAs($this->givenUser()) ->get('/invoices/store/xlsx'); Excel::assertStored('filename.xlsx', 'diskName'); Excel::assertStored('filename.xlsx', 'diskName', function(InvoicesExport $export) { return true; }); // When passing the callback as 2nd param, the disk will be the default disk. Excel::assertStored('filename.xlsx', function(InvoicesExport $export) { return true; }); } ``` -------------------------------- ### Selecting multiple sheets by index (Laravel Excel) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/import/select.md Demonstrates how to load multiple sheets from an Excel file by providing their zero-based indices as separate arguments to the `selectSheetsByIndex` method. ```PHP Excel::selectSheetsByIndex(0, 1)->load(); ``` -------------------------------- ### Importing from Specific Disk (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/basics.md Shows how to import a file from a specific filesystem disk (e.g., 's3') by providing the disk name as the third parameter to the Excel::import method. ```php Excel::import(new UsersImport, 'users.xlsx', 's3'); ``` -------------------------------- ### Instantiating a Drawing Object - PhpSpreadsheet - PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/drawings.md Demonstrates the basic instantiation of a `\PhpOffice\PhpSpreadsheet\Worksheet\Drawing` object and setting its core properties like name, description, file path, and height before adding it to a worksheet. ```php $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $drawing->setName('Logo'); $drawing->setDescription('This is my logo'); $drawing->setPath(public_path('/img/logo.jpg')); $drawing->setHeight(90); ``` -------------------------------- ### Using Laravel Excel Import with Progress Bar in Console Command (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/progress-bar.md This PHP snippet shows a Laravel console command that utilizes the `UsersImport` class (implementing `WithProgressBar`). It sets up the command signature and description, and the `handle` method initiates the import, attaching the command's output to display the progress bar and messages. ```php output->title('Starting import'); (new UsersImport)->withOutput($this->output)->import('users.xlsx'); $this->output->success('Import successful'); } } ``` -------------------------------- ### Running PHPUnit Tests (Shell) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/csv/1.0/getting-started/contributing.md This command executes the PHPUnit test suite for the project. Contributors are required to run tests to ensure their changes do not introduce regressions and to add new tests for their features or bug fixes. ```Shell vendor/bin/phpunit ``` -------------------------------- ### Set Sheet Borders (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/export/sheet-styling.md Applies borders to the sheet. Examples show setting borders for the entire sheet, a single cell, and a range of cells with a specified style. ```PHP // Sets all borders $sheet->setAllBorders('thin'); // Set border for cells $sheet->setBorder('A1', 'thin'); // Set border for range $sheet->setBorder('A1:F10', 'thin'); ``` -------------------------------- ### Importing from Full Path (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/basics.md Explains how to import a file using its absolute file path, bypassing the need to specify a filesystem disk. This is suitable for files not managed by configured disks. ```php Excel::import(new UsersImport, storage_path('users.xlsx')); ``` -------------------------------- ### Downloading Basic FromQuery Export in Laravel Excel (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/from-query.md Demonstrates how to instantiate the `InvoicesExport` class and call the `download()` method to initiate the file download with a specified filename (`invoices.xlsx`). ```php return (new InvoicesExport)->download('invoices.xlsx'); ``` -------------------------------- ### Get Default Workbook Style (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/export/call.md Demonstrates how to call the native PHPExcel `getDefaultStyle` method on the `$excel` workbook object to retrieve the default style settings for the workbook. ```PHP $excel->getDefaultStyle(); ``` -------------------------------- ### Exporting to PDF using TCPDF with Laravel Excel Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/export-formats.md Explicitly exports data using the Laravel Excel library to the PDF format using the TCPDF rendering library. Requires TCPDF to be installed separately. ```PHP return Excel::download(new InvoicesExport, 'invoices.pdf', \Maatwebsite\Excel\Excel::TCPDF); ``` -------------------------------- ### Exporting to PDF using DOMPDF with Laravel Excel Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/export-formats.md Explicitly exports data using the Laravel Excel library to the PDF format using the DOMPDF rendering library. Requires DOMPDF to be installed separately. ```PHP return Excel::download(new InvoicesExport, 'invoices.pdf', \Maatwebsite\Excel\Excel::DOMPDF); ``` -------------------------------- ### Downloading FromQuery Export (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/from-query.md Shows how to initiate the download for an export class that implements the `FromQuery` concern. The `download()` method triggers the export process based on the query defined in the class. ```PHP return (new InvoicesExport)->download('invoices.xlsx'); ``` -------------------------------- ### Exporting to PDF using MPDF with Laravel Excel Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/exports/export-formats.md Explicitly exports data using the Laravel Excel library to the PDF format using the MPDF rendering library. Requires MPDF to be installed separately. ```PHP return Excel::download(new InvoicesExport, 'invoices.pdf', \Maatwebsite\Excel\Excel::MPDF); ``` -------------------------------- ### Importing Excel File from Default Disk (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.1/imports/basics.md Demonstrates how to import an Excel file located on the default filesystem disk using the `Excel::import` method. It takes an instance of the import class (implementing a concern like ToModel) and the filename as arguments. ```php Excel::import(new UsersImport, 'users.xlsx'); ``` -------------------------------- ### Creating Excel File with Callback (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/export/README.md Creates a new Excel file with the specified filename and provides a callback function. The callback receives a `LaravelExcelWriter` instance, allowing for further manipulation and configuration of the file content and properties within the creation process. ```PHP Excel::create('Filename', function($excel) { // Call writer methods here }); ``` -------------------------------- ### Storing a CSV Export on Disk (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/csv/1.0/exports/collection.md Demonstrates a Laravel controller method storeCsv that uses the Csv facade to store the UsersExport instance to a specified disk (s3 in this example) with the filename users.csv. ```php public function storeCsv() { return Csv::store(new UsersExport, 'users.csv', 's3'); } ``` -------------------------------- ### Retrieving Collected Import Errors After Import in PHP Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/imports/validation.md Example demonstrating how to instantiate an import class using `SkipsErrors`, run the import, and access collected errors via the `errors()` method. ```php $import = new UsersImport(); $import->import('users.xlsx'); dd($import->errors()); ``` -------------------------------- ### Storing an Export to a Specific Disk Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/4.x/exports/exporting.md The `Excel::store()` method accepts an optional third parameter to specify the storage disk where the file should be saved. This example saves the export to the `s3` disk. ```php Excel::store(new UsersExport, 'users.xlsx', 's3'); ``` -------------------------------- ### Converting Results to Object (Laravel Excel, PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/import/results.md Shows how to convert the imported results into an object structure using the ->toObject() method, offering an alternative to ->get() or ->all() when an object is preferred. ```PHP $reader->toObject(); ``` -------------------------------- ### Using Collection Methods on Results (Laravel Excel, PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/import/results.md Illustrates that the results returned by ->get() or ->all() are collections, allowing the use of standard Laravel collection methods like groupBy. ```PHP // E.g. group the results $reader->get()->groupBy('firstname'); ``` -------------------------------- ### Bind Laravel Excel Manager to Container Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/getting-started/installation.md Bind the 'excel' container instance to your own custom class within a service provider or similar location to manage dependencies via the Laravel service container. ```php $this->app->bind(YourCustomExporter::class, function() { return new YourCustomExporter($this->app['excel']); }); ``` -------------------------------- ### Creating Basic Excel File (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/export/README.md Creates a new Excel file with the specified filename using the basic `Excel::create` method. This is the simplest way to initialize an export without immediate content or property manipulation. ```PHP Excel::create('Filename'); ``` -------------------------------- ### Downloading FromQuery with Setter Method (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/from-query.md Shows how to download an export where the `FromQuery` class accepts a parameter via a setter method. The setter method is called on the export instance before chaining the `download()` method. ```PHP return (new InvoicesExport)->forYear(2018)->download('invoices.xlsx'); ``` -------------------------------- ### Selecting multiple sheets by name (Laravel Excel) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/2.1/import/select.md Shows how to load multiple sheets from an Excel file by providing their names as separate arguments to the `selectSheets` method. ```PHP Excel::selectSheets('sheet1', 'sheet2')->load(); ``` -------------------------------- ### Manually Register Laravel Excel Service Provider Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/getting-started/installation.md Although auto-discovered by default in recent Laravel versions, you can manually register the Excel Service Provider by adding it to the 'providers' array in your config/app.php file. ```php 'providers' => [ /* * Package Service Providers... */ Maatwebsite\Excel\ExcelServiceProvider::class, ] ``` -------------------------------- ### Downloading Exportable Class Instance (PHP) Source: https://github.com/spartnernl/laravel-excel-docs/blob/master/3.0/exports/exportables.md This PHP snippet demonstrates how to download an export directly from an instance of a class that uses the Exportable trait. The download() method initiates the file download with the specified filename. This approach bypasses the need for the Excel facade. ```php return (new InvoicesExport)->download('invoices.xlsx'); ```