How to redirect to a generated pdf in laravel?

Member

by dedrick , in category: PHP Frameworks , 3 months ago

How to redirect to a generated pdf in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 3 months ago

@dedrick 

To redirect to a generated PDF in Laravel, you can first save the PDF file in the storage directory and then return a redirect response to the URL of the PDF file. Here's an example:

  1. Save the PDF file in the storage directory:
1
2
3
$pdf = PDF::loadView('pdf.my_pdf_view'); // Generate the PDF
$filename = 'my_pdf_file.pdf';
$pdf->save(storage_path('app/public/'.$filename)); // Save the PDF in the storage directory


  1. Return a redirect response to the URL of the PDF file:
1
return redirect('/storage/'.$filename);


Make sure to replace 'pdf.my_pdf_view' with the name of the view used to generate the PDF and 'my_pdf_file.pdf' with the desired filename for the PDF file.


Additionally, you may need to configure your filesystem in Laravel to enable the storage of public files. You can do this by updating the 'disks' array in your config/filesystems.php file:

1
2
3
4
5
6
'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
],


This will allow you to store and access the PDF files in the 'public' disk of the storage directory.