In Laravel, you have access to third-party packages because of the composer. Using composer, you can install any package in Laravel. The composer provides the package dependencies in PHP. Here, we’ll be talking about the Laravel DOM PDF. This is an open-source package available on Github to generate the PDF. By using this package, you can easily create PDF in Laravel. In this post, I will be implementing the feature to export the content as a PDF in Laravel 8. So, PDF stands for portable document format. It helps us for providing the invoices, user manuals, eBooks, application forms, etc. So, let’s start by creating a new project in Laravel 8.
Prerequisites
To start the Laravel 8 project, you will require the following tools configured in your system.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
For creating the project, I am going to use the composer here. Instead of this, you can use the Laravel installer.
Create New Project For Laravel DOM PDF
To create a new project, firstly, open the terminal or command prompt. Then hit the below command.
composer create-project --prefer-dist laravel/laravel dompdf
This will take a couple of minutes to install the Laravel 8 inside the folder.
Once the installation is completed, let’s move to the next step. Here, I will be creating a database and connect with our application.
RESTful APIs For Todo App Using Passport Auth in Laravel 8
Create and Configure Database
For the database, I am using MySQL. Actually, for exporting the data to a PDF, I will be fetching data from the database. Hence, we required to connect with the database first.
CREATE DATABASE dom_pdf;
Once, the database has been created, it requires to configure in the Laravel 8 project. Hence, just open the .env file of the project, and put the database credentials there.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_pdf
DB_USERNAME=root
DB_PASSWORD=root
After connecting the database, we will proceed to the installation of the package.
How to Implement Invisible reCAPTCHA in Laravel 8
Install Laravel DOM PDF Package
You will require to install the package for generating the PDF file in Laravel. You can search for the dom pdf package in the composer. But, if you have the package name then directly install it. So, simply paste the below command in the terminal. Also, make sure you are inside the project directory.
composer require barryvdh/laravel-dompdf
Here, the above command will install the configuration of the dom pdf package.
Create Authentication in Laravel 8 Using Laravel Breeze
Configure DOM PDF Package in Laravel 8
Before using this package in Laravel 8, it requires registering its service provider. So, just follow the simple steps here.
- Firstly, open the config/app.php and then add inside the providers array add the below provider.
- Secondly, in the aliases array, add the alias for the dompdf.
'providers' => [
…
…
…
Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
…
…
…
'PDF' => Barryvdh\DomPDF\Facade::class,
]
After the configuration of the provider and alias, it will require to publish it using vendor publish command.
php artisan vendor:publish
The above command will ask for which you want to publish the configuration. Here, I chosen for the dompdf. You can see in the below result.
After the publishing you will see one file named dompdf.php in the config folder.
How to Configure PHPMailer in Laravel 8 For Sending Email
Create Model and Migration
Here, we already have the User model and migration file. So, firstly, I will check the columns in the user migration file.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Next, I will add the fillable data for the User.php (model).
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Lastly, we have to migrate the schema of the users table. So, just hit the below command for the migration.
php artisan migrate
Here, the migration has been completed. Now, we can proceed for the data dumping on the users table.
In the next step, I will be using the factory() class to insert some dummy records into the Users table.
Laravel 8 Client Side Form Validation Using jQuery
Create Factory Class For User Table
We already have the default factory() class for the users table. You need to check the fields are the same for which you will be inserting the records. The factory class, generates dummy records from the faker class. It generates some fake values for the specified attributes.
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
In the above snippet, you can see the fields are specified by default. You no need to change until you added some new fields in the migration.
Insert Dummy Records Using Tinker
For inserting the dummy records in the users table, you will have to run the tinker command. Please take a look at the below result.
php artisan tinker
User::factory()->count(500)->create()
Here, I have specified the records to be inserted into the users table.
I have triggered the User factory() here. So, it is clearly specified through which model it will be inserting the records.
Now, we have the dummy records. In the next step, we have to display these records on a view. After that, we will create the functionality to export data as a PDF using the Laravel DOM PDF.
But, for fetching the data, I will create a controller first. So, just create one.
Create RESTful APIs in Laravel 8 Using Sanctum Auth
Create a Controller For Laravel 8 DOM PDF
Here, I will create a controller for the Users. So, just hitting the below command in the terminal.
php artisan make:controller UserController
After creating the controller, just put down the below code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use PDF;
class UserController extends Controller
{
/**
* Return Users data to users view
*
* @return void
*/
public function index()
{
$users = User::all();
return view('users', compact('users'));
}
/**
* Export content to PDF with View
*
* @return void
*/
public function downloadPdf()
{
$users = User::all();
// share data to view
view()->share('users-pdf',$users);
$pdf = PDF::loadView('users-pdf', ['users' => $users]);
return $pdf->download('users.pdf');
}
}
The above functions will require routes to show the results on the browser. Hence, let’s add some routes.
Add Routes For Generating PDF
Here, we will create two routes for the above two functions.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('users', [UserController::class, 'index']);
Route::get('export-pdf', [UserController::class, 'downloadPdf'])->name('export-pdf');
After creating the routes, let’s add the views for implementing export to PDF functionality.
Create RESTful APIs in Laravel 8 Using Passport Auth
Create Views
Here, I will create two views. In the first view, I will just display the content which will be coming through the database. There will be a button for exporting content to PDF. When the button will be clicked, it will call to another route and that route will have a function. Inside that function, the same data will be called through the database but this time, it will export with different view.
So, just create these views-
- users.blade.php and
- users-pdf.blade.php
After creating both views, put down the below codes one by one. Firstly, put the code in the users.blade.php file.
<!doctype html>
<html lang="en">
<head>
<title>Laravel 8 DOM PDF Tutorial - Programming Fields</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container py-5">
<div class="row">
<div class="col-xl-12 text-right">
<a href="{{ route('export-pdf') }}" class="btn btn-success btn-sm">Export to PDF</a>
</div>
</div>
<div class="card mt-4">
<div class="card-header">
<h5 class="card-title font-weight-bold">Laravel 8 DOM PDF Tutorial</h4>
</div>
<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Created</th>
</tr>
</thead>
<tbody>
@forelse ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ \Carbon\Carbon::parse($user->created_at)->diffForHumans() }}</td>
</tr>
@empty
@endforelse
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
When you will run the project and open the URL – http://localhost:8000/users
then you will have the below result.
In the above screenshot, you can see, there is a button to export the data to PDF. When you will click on that, it will hit to the next function. So, for generating the PDF with the same content here, we required a tablular form. Therefore, in the second view (users-pdf.blade.php) file, add the below snippet.
<!doctype html>
<html lang="en">
<head>
<title>Laravel 8 DOM PDF Tutorial - Programming Fields</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
table {
font-size: 12px;
}
</style>
</head>
<body>
<div class="container py-5">
<div class="card mt-4">
<div class="card-header">
<h5 class="card-title font-weight-bold">Laravel 8 DOM PDF Tutorial</h4>
</div>
<div class="card-body">
<table class="table table-bordered mt-5">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Created</th>
</tr>
</thead>
<tbody>
@forelse ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ \Carbon\Carbon::parse($user->created_at)->diffForHumans() }}</td>
</tr>
@empty
@endforelse
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
When the PDF is exported, it will look like this.
How to Upload Image in CKEditor 5 Using Laravel 8
Conclusion
By using Laravel DOM PDF library we have created the PDF file using HTML. You can design the template file as per your requirement. I have just shown a basic approach to generate the PDF file in Laravel 8. This way, you can export any data to the PDF file. So, I assume this post, will be very helplful for you. Thank you.
Leave a Reply