I have tested this code in Laravel 6,7,8 & 9.
Steps to Follow
- Install PDF Library (barryvdh/laravel-dompdf)
- Add Provider and alias in config/app.php
- Create Route and point it to any controller method
composer require barryvdh/laravel-dompdf
config/app.php
'providers' => [
....
Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
....
'PDF' => Barryvdh\DomPDF\Facade::class,
]
<?php
namespace App\Http\Controllers;
use App\Models\docs;
use Illuminate\Http\Request;
use PDF;
use Dompdf\Dompdf;
class DocsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$docs = docs::get();
$data = [
'docsList'=> $docs
];
$file_title = "docs.pdf";
$pdf = PDF::loadView('docs.list', $data);
return $pdf->download($file_title);
}
All done! This will download your view in PDF format.
Note: As of Laravel 9 this doesnt work on local machine, but as soon as you update your code online, this works perfectly. This is due to missing php modules.