Hi guys, I have a small question regarding dependency injection in combination with the Maatwebsite Excel package.
So I followed there docs and have the same code as they do. However I want to use the request to generate a better title for the excel sheet. So I though, let's inject the request in the controller.
Now comes the strange part, this is working for The MyRapportExportHandler class but not for the MyRapportExport class. So first the controller. This will create the MyRapportExport class and call the handler for it.
// ExcelController.php
public function myRapport(MyRapportExport $export)
{
$export->handleExport();
}
As the documentation said I need to extend the NewExcelFile class and add the method getFileName, however the $request return null here...
// MyRapportExport.php
use Illuminate\Foundation\Application;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Files\NewExcelFile;
use Illuminate\Http\Request;
class MyRapportExport extends NewExcelFile
{
protected $request;
public function __construct(Application $app, Excel $excel, Request $request)
{
parent::__construct($app, $excel);
$this->request = $request;
}
public function getFilename()
{
dd($this->request); // This return null...
return "Rapport for " . $this->request->get('year');
}
}
The strange thing is that it does work in the handler class
// MyRapportExportHandler.php
use Illuminate\Http\Request;
use Maatwebsite\Excel\Files\ExportHandler;
class MyRapportExportHandler implements ExportHandler
{
protected $request;
public function __construct(Request $request) {
$this->request = $request; // This is a valid request object
}
public function handle($export)
{
return $export->sheet($this->getSheetTitle(), function ($sheet) {
$sheet->fromArray(['data', 'data']);
})->download('xlsx');
}
protected function getSheetTitle()
{
return 'Year ' . $this->request->get('year', date('Y'));
}
}
So any clues would be appreciated!
Package documentation: http://www.maatwebsite.nl/laravel-excel/docs/export#injection