My answer is for those that are trying to download excel file in laravel using api route. It's important to note that I was using laravel Jobs and dispatch stuff. And I was sending the return request to a json_success helper function which was actually converting my download response to a json. So I simply removed anything that comes in between downloading file. And it's working fine now. As I am using repository structure so I will try to post each function from repository to controller. Dispatch was also giving me 0 which wasn't letting the file to be downloaded.
Before
// export service data // Repository function
public function exportInsuranceServices($insuranceId)
{
return dispatch_sync(new ExportInsuranceServiceJob($insuranceId));
}
this is the job class
class ExportInsuranceServiceJob implements ShouldQueue
{
use Dispatchable, Queueable;
protected $insuranceId;
public function __construct($insuranceId) {
$this->insuranceId = $insuranceId;
}
public function handle()
{
return Excel::download(new ExportInsuranceService($this->insuranceId), 'insuranceService.xlsx',null, [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
])->getStatusCode();
}
}
Export Insurance Service
class ExportInsuranceService implements FromQuery, WithHeadings, ShouldAutoSize
{
use Exportable;
protected $insuranceId;
public function __construct($insuranceId) {
$this->insuranceId = $insuranceId;
}
public function query()
{
return InsuranceService::query()
->where('insurance_id',decryptId($this->insuranceId))
->select('name_en', 'name_ar','code', 'price','original_price', 'insurance_id','service_id','status');
}
public function headings(): array
{
return [
'name_en', 'name_ar','code', 'price','original_price','insurance_id', 'service_id','status'
];
}
}
Controller function
/**
* Export Insurance Services by insurance id.
*/
public function export($insurance_id,InsuranceServiceRepository $repo)
{
return jsend_success($repo->exportInsuranceServices($insurance_id));
}
After
// export service data. Here I have removed the job class
public function exportInsuranceServices($insuranceId)
{
return Excel::download(new ExportInsuranceService($insuranceId), 'insuranceService.xlsx');
}
/**
* Export Insurance Services by insurance id. Here I have removed jsend_success helper function
*/
public function export($insurance_id,InsuranceServiceRepository $repo)
{
return $repo->exportInsuranceServices($insurance_id);
}
The ExportInsuranceService is the same as already shown