When you move the PDF generation and streaming logic from a controller to a service, you need to ensure that the service method returns the response back to the controller, which then returns it to the client. In your current setup, it seems like the service method is not returning the PDF stream response, which is why the PDF page appears white.
Here's how you can modify your code to ensure the response is properly returned:
- Modify the Service Method: Ensure that the
trainingmethod in yourFileServicereturns the PDF stream.
public function training(Training $training, $download = true)
{
$employees = $training->employees->sortBy(['lastname', 'firstname']);
$pdf = PDF::loadView('files.training', compact('training', 'employees'));
$pdf->setPaper('a4', 'portrait');
if ($download) {
return $pdf->stream($training->society->name.' - '.$training->name.'.pdf');
} else {
$folder = storage_path('app/documents/'.$training->id);
if (!is_dir($folder)) {
mkdir($folder, 0700, false);
}
$pdf->save(storage_path('app/documents/'.$training->id.'/file.pdf'));
}
}
- Modify the Controller Method: Ensure that the controller method captures and returns the response from the service.
public function training(Training $training, $download = true)
{
$this->authorize('export', $training);
return (new FileService)->training($training, $download);
}
By returning the result of the stream() method from the service back to the controller, and then from the controller to the client, you should be able to see the PDF as expected. This ensures that the HTTP response is properly handled and sent back to the browser.