How to Generate PDF in Laravel 11 with DomPDF

To generate a PDF in the Laravel application, use the “dompdf package.” Dompdf is an HTML-to-PDF converter.

To export into PDF, We need to write the view file. Then, we will write the HTML code and load data dynamically from the database as required. After that, we will export this view as a PDF file.

Step 1: Create a laravel project

Install Laravel using the following command.

composer create-project --prefer-dist laravel/laravel laravelPDF

You need to install the laravel/ui package.

composer require laravel/ui

Now, add the Bootstrap library using laravel/ui:

php artisan ui bootstrap

Step: 2 Download the laravel-dompdf package

composer require barryvdh/laravel-dompdf

Step: 3 Configure the package in Laravel

Go to bootstrap >> provider.php file and add the below code:

<?php

return [
    App\Providers\AppServiceProvider::class,
    Barryvdh\DomPDF\ServiceProvider::class,
];

Here, we are registering the ServiceProvider of the barryvdh package.

Step 4: Connecting Laravel with Database

Open phpmyadmin and create a new Database like this:

database_laravelpdf

Now, open the .env file, edit these variables, and put your database name, username, and password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=laravelpdf
DB_USERNAME=root
DB_PASSWORD=root

Keep in mind that I am using MAMP; these are my credentials, and it is local.

Step 5: Create model and migration files

We will create model and migration files using the following command.

php artisan make:model Disneyplus -m

Go to the [timestamp].create_disneypluses_table.php file and add the columns.

public function up()
{
        Schema::create('disneypluses', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('show_name');
            $table->string('series');
            $table->string('lead_actor');
            $table->timestamps();
        });
}
Now, migrate the database using the following command.
php artisan migrate

Step 6: Create a controller and routes

The next step is to create a DisneyplusController.php file.

php artisan make:controller DisneyplusController

Now, add the two routes inside the routes >> web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DisneyPlusController;


Route::get('/', function () {
    return view('welcome');
});

Route::get('disneyplus/create', [DisneyPlusController::class, 'create'])->name("disneyplus.create");
Route::post('disneyplus/store', [DisneyPlusController::class, 'store'])->name("disneyplus.store");

Create two methods inside the DisneyplusController.php file. 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;


class DisneyplusController extends Controller

{

public function create()
{

}

public function store()
{

}



}

Don’t forget to import the PDF module.

Step 7: Create a layout blade file

Inside the resources >> views folder, create a new file called layout.blade.php.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Laravel PDF Generation</title>
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
    <!-- Scripts -->
    @vite(['resources/sass/app.scss', 'resources/js/app.js'])
</body>
</html>

Step: 8 Create a form blade file for input the data

Inside the views folder, create the form.blade.php file.  Add the following code:

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Disneyplus Shows
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('disneyplus.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Show Name:</label>
              <input type="text" class="form-control" name="show_name"/>
          </div>
          <div class="form-group">
              <label for="series">Series :</label>
              <input type="text" class="form-control" name="series"/>
          </div>
          <div class="form-group">
              <label for="actor">Show Lead Actor :</label>
              <input type="text" class="form-control" name="lead_actor"/>
          </div>
          </br>
          <button type="submit" class="btn btn-primary">Create Show</button>
      </form>
  </div>
</div>
@endsection

Step 9: Store data in the database

We will write the two functions inside the DisneyplusController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Disneyplus;
use Barryvdh\DomPDF\Facade\Pdf;

class DisneyplusController extends Controller
{
    public function create()
    {
        return view('form');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('disneyplus/list');
    }
}

In the above file, we first show the form file, and then, inside the store function, we check for validation and store the data in the database.

We haven’t created the disneyplus/list route yet but will do it later.

Add the fillable fields inside the Disneyplus.php model file.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Disneyplus extends Model
{
    use HasFactory;
    protected $fillable = ['show_name', 'series', 'lead_actor'];
}

Go to this route: http://localhost:8000/disneyplus/create

Disneyplus_create

You will see one form. Try to save the data; if everything in the code is right, you will see one entry in the database.

data_entry

Step 10: Create a view file to display the data

Before creating a view file, we must add one route inside the web.php.

//web.php
 
Route::get('disneyplus/list', [DisneyPlusController::class, 'index'])->name('disneyplus.index');

Create a view file called list.blade.php file. Add the following code.

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Show Name</th>
    <th>Series</th>
    <th>Lead Actor</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

Now, add the code inside the index() function to the DisneyplusController.php file.

public function index()
    {
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
    }

Now, go to http://localhost:8000/disneyplus/list

You will see the listing of the shows.

disneyplus_list

Step: 11 Create a route to download the PDF file

Add the following code inside the route file.

// web.php 

Route::get('/downloadPDF/{id}',[DisneyPlusController::class, 'downloadPDF'])->name('disneyplus.pdf');

Update the list.blade.php file and add the Download PDF link.

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Show Name</th>
    <th>Series</th>
    <th>Lead Actor</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
      <td><a href="{{ route('disneyplus.pdf', $show->id)}}">Download PDF</a></td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

action_link

Step: 12 Create a pdf.blade.php file to design our pdf

You can create the new DOMPDF instance and load an HTML string, file, or blade view name. You can save it to the file or stream. Inside the views folder, create one pdf.blade.php file and add the following code.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
          {{$show->show_name}}        
          {{$show->series}}
          {{$show->lead_actor}}
  </body>
</html>

Step: 13 Write a controller function to download the PDF

Write the following code inside the DisneyplusController.php file.

// DisneyplusController.php

  public function downloadPDF($id) 
    {
        $show = Disneyplus::find($id);
        $pdf = PDF::loadView('pdf', compact('show'));
        return $pdf->download('disney.pdf');
    }

Go to  http://localhost:8000/disneyplus/list and click on the Download PDF link.

It downloads the PDF file and opens it; you will see the data.

disneyplus_pdf

14 thoughts on “How to Generate PDF in Laravel 11 with DomPDF”

  1. Hi Krunal, great tutorial!!

    I´m just starting with Laravel and this was a super useful explanation
    to me.

    Thanks and keep helping people to leverage knowledge on this great framework

    People like you make a great difference
    Cheers
    Mauricio

    Reply
  2. Well Done, Krunal! This was a very helpful tutorial.
    Two small suggestions:
    1. Why not include the “use PDF; ” directive in your DisneyplusController script, rather than as a sidenote?
    2. It would save a few keystrokes to use “php artisan make:controller DisneyplusController -r” and lete the system insert the index, store and create functions.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.