Here is an example of how to generate a PDF and send an email in Laravel 10:
- Install the
barryvdh/laravel-dompdf
package. This package provides a simple way to generate PDF files in Laravel. You can install it using the following command:
composer require barryvdh/laravel-dompdf
- Publish the
dompdf
configuration file. This file contains the configuration options for thebarryvdh/laravel-dompdf
package. You can publish it using the following command:
php artisan vendor:publish --provider="Barryvdh\DomPDF\DomPDFServiceProvider"
- Create a controller to generate the PDF file. Create a new file called
PDFController.php
in yourapp/Http/Controllers
directory. In this file, add the following code:
PHP
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
class PDFController extends Controller
{
public function generatePDF()
{
$data = [
'title' => 'My PDF Document',
'content' => 'This is the content of my PDF document.',
];
$pdf = PDF::loadView('pdf.example', $data);
return $pdf->download('my-pdf.pdf');
}
}
- Create a view file to render the PDF content. Create a new file called
pdf.example.blade.php
in yourresources/views
directory. In this file, add the following code:
HTML
<!DOCTYPE html>
<html>
<head>
<title>My PDF Document</title>
</head>
<body>
<h1>{{ $title }}</h1>
<p>{{ $content }}</p>
</body>
</html>
- Create a route to your controller. In your
routes/web.php
file, add the following route:
Route::get('/pdf', 'PDFController@generatePDF');
- Test the route. In your terminal, run the following command to test the route:
php artisan serve
Then, open a browser and navigate to the following URL:
http://localhost:8000/pdf
This will generate a PDF file and download it to your computer.
Here is an explanation of the code:
- The
PDFController
class extends theController
class. - The
generatePDF()
method generates the PDF file and returns it as a download. - The
loadView()
method loads thepdf.example
view file and passes the data array to it. - The
download()
method downloads the PDF file to the user’s computer.