Laravel 8 Export view to PDF - Convert MySql data to PDF

Last updated Sep 29, 2021

While we working with web applications, we will display the data in the views. Sometimes we may requires export these data into PDF formats. So in this laravel 8 example tutorial we will learn how to export data to pdf  (Export tables data to PDF).

To achieve this functionality we will use DomPDF package in this example. So let's get started

 

Step 1: Create new PHP project with Laravel 8.

Open terminal set path where you want to create project then run below command

composer create-project laravel/laravel laravel-export-pdf

 

Step 2: Install DomPDF packages

We have created our laravel project, now in the terminal move to current created project folder and run below Command to install DomPDF packages using composer.

composer require barryvdh/laravel-dompdf

 

Step 3: Configure DomPDF with our project

To configure DomPDF with currently created project, open app.php inside config/app.php  and add below code under respected places

Inside 'Providers'

Barryvdh\DomPDF\ServiceProvider::class,

 

Inside 'aliases'

'PDF' => Barryvdh\DomPDF\Facade::class,

 

We doe with DomPDF configuration

 

Step 4: Create Product model

Let's create a model with below command, in this example we are going create a Product model

php artisan make:model Product -m

 

Now we created just empty Product mode, our product contains few fields, so let's add fields to our product model

Our Product model would be like this, this file will be under app/Models /Product.php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;
   public $fillable = 
[
   'sku',
   'Name',
   'amount',
   'price',
   'description'
];
}

 

Now open our database table under database/migrations/ x_create_product_table.php. this x_ would be change based on that current time.

Add our product fields into database like below

 

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
         $table-> string ('sku');
            $table-> string ('name');
            $table-> string ('amount');
            $table-> float ('price');
            $table-> text ('description');
            $table->timestamps();
        });
      
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

 

Step 5: Database configuration

Let's create a database, let's open PHPMyadmin and create a database with respected name, here i have created database with name "laravel8"

To configure database with current project open .env file and update your database details like below

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

 

Step 6: Generate Fake data

We are created our database and table, but we don't have any data inside our table, so let's add some fake data by following the below process.

 

Let's create a ProductFactory under database\factories\ProductFactory.php and add below code inside that file

namespace Database\Factories;

use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class ProductFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Product::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
      
      'sku' => $this->faker->randomNumber(),
                'name' => $this->faker->word(),
                'amount' => $this->faker->numberBetween(1, 20),
                'price' => $this->faker->numberBetween(10, 500),
                'description' => $this->faker->text(),
                'created_at' => '00:00:00',
                'updated_at' => '00:00:00'
            
        ];
    }

    
}

 

Now seeds in command line

php artisan db:seed

 

This will generate some fakedata under Product table

 

How do i export data to pdf from mysql database in laravel 8 php

 

Step 7: Create Controller

We are ready with database, need to create controllers to handle the data from Database

Let's create a ProductController by running below code

php artisan make:controller ProductoController

 

 

Now open ProductController.php file from app/Http /Controllers/ProductController.php  and create two functions to fetch the data from Database and generate pdf from data.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use PDF;

class ProductController extends Controller
{
    public function index () {
        $products = Product::all();
        return view('index', compact ('products'));
    }
   
   public function createPDF () {
        // Retrieve all products from the db
        $products = Product::all();
        view()->share ('products', $products);
        $pdf = PDF ::loadView ('index', $products);
        return $pdf->download ('file-pdf.pdf');
    }
}

 

Step 8: Create View

We are ready with Mode, Controller now we need to create views to display data from database to screen. Let's create a index.php file under resources\views\index.balde.php and add below code to retrive data from database in php and display in table.

 

<! DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <meta http-equiv = "X-UA-Compatible" content = "IE = edge">
    <meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
    <title> Laravel 8 PDF </title>
    <! - Bootstrap5 CSS ->
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">

   <style>
   table, th, td {
  border: 1px solid black;
}
 th, td {
  border-color: #96D4D4;
 
}
.col1{
   width:100px;
}
.col2{
   width:500px;;
}

   </style>
</head>
<body>
    <div class = "container mt-4">
        <div class = "row">
            <div class = "col-md-8">
                <h2> Product list </h2>
            </div>
            <div class = "col-md-4">
                <div class = "mb-4 d-flex justify-content-end">
                    <a class="btn btn-primary" href="http://127.0.0.1:8000/product/pdf"> Export to PDF </a>
                </div>
            </div>
        </div>
        <div class = "row">
            <div class = "col-md-12">
                <table class = "table">
                    <caption> Product list </caption>
                    <thead>
                      <tr>
                        <th scope = "col" class="col1"> SKU </th>
                        <th scope = "col" class="col1"> Name </th>
                        <th scope = "col" class="col1"> Amount </th>
                        <th scope = "col" class="col1"> Price </th>
                        <th scope = "col" class="col2"> Description </th>
                      </tr>
                    </thead>
                    <tbody>
                        @foreach ($products as $product)
                        <tr>
                            <th  class="col1" scope = "row"> {{$product-> sku}} </th>
                            <td class="col1" > {{$product-> name}} </td>
                            <td class="col1" > {{$product-> quantity}} </td>
                            <td class="col1" > {{$product-> price}} </td>
                            <td class="col2"> {{$product-> description}} </td>
                        </tr>
                        @endforeach
                    </tbody>
                  </table>
            </div>
        </div>
    </div>
   
    <script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KinkN" crossorigin="anonymous"></script>
   <!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>


    <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"> </script>
   
</body>
</html>

 

Step 9: Routes configuration

To access our web data we need to create route to our end point. Let's open routes/web.php file and add below routes to access our view.

Route::get('/product', [App\Http\Controllers\ProductController::class, 'index'])->name('ProductController.index');
Route::get('/product/pdf', [App\Http\Controllers\ProductController::class, 'createPDF'])->name('product.pdf');

 

We done with our laravel8 project which will export data to PDF file from database. If you want read about Create Rest API with Laravel8 

 

Step 10: Start our server by running below command

php artisan serve

 

if everything works fine we will see our server will run at http://127.0.0.1:8000

Now open http://127.0.0.1:8000/product in your respected browsers

You will see the below out put on the screen.

Export data to pdf laravel php

 

Now click on Export to PDF button it will generate PDF file with requested data.

 

Conclusion: In this laravel8 example we created a project which will export data to PDF from mysql database using the DomPDF library. DomPDF  is one of the best packages in laravel, so we have created example of Laravel 8 export view to PDF by this package

 

Read more about

PHP String paraser example

How to find string length in php

School Managment System project with PHP

PHP CRM Project for beginners

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

4490 Views