How To Generate PDF In Laravel

devquora
devquora

Posted On: May 18, 2022

How To Generate PDF In Laravel

 

Hello, friends today we are going to see How To Generate PDF In Laravel 6. In any Laravel application PDF generation is one of the important tasks. You need to generate a pdf of invoices for the product and for another purpose. Here in this article, we are going to use barryvdh/laravel-dompdf package for generating our PDF.

Prerequisite: I am assuming that you have already installed the Laravel 6 Framework on your server.

Getting started with Laravel 6 pdf generator Tutorial

  • 1. Installing the laravel-dompdf package through composer.
  • 2. Configuring barryvdh/laravel-dompdf package in our Laravel application.
  • 3. Creating the Layout File for our application.
  • 4. Creating a forming blade for inputting order details from the user.
  • 5. Adding routes for our application.
  • 6. Creating migration files for the order_details table.
  • 7. Running order_details table migration.
  • 8. Creating a Model file for our table.
  • 9. Creating a Laravel controller for saving order data.
  • 10. Creating a view for displaying order Data.
  • 11. Creating a route for downloading files.
  • 12. Creating a pdf.blade.php file for designing our PDF.
  • 13. Writing Function to generate and download PDF file in Controller.

Also Read: Best Laravel Interview Questions

Step1: Installing laravel-dompdf package through composer

Open your command prompt and cd to your Laravel directory, then run the below command.

composer require barryvdh/laravel-dompdf

Step2: Configuring barryvdh/laravel-dompdf package

For configuration please open the config/app.php file and add the following configuration in the provider and aliases array.

'providers' => [
    ....
    Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
    ....
    'PDF' => Barryvdh\DomPDF\Facade::class,
],

The above step is required in order to register an external package and make its alias.

Step3: Creating a layout for our application

Create a directory named layouts in resources/view/ folder. After that create the layout.blade.php file and the following line of code and save it.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/app.css">
  </head>
  <body>
      <div class="container">
          @yield('content')
      </div>
  </body>
</html>

Creating a forming blade for inputting order details from the user.

In this step, we are going to create a form by inputting order details from the customer. Create a new file named order.blade.php under the resources/view/order folder and place the following code in it.

@extends('layout')
@section('content')
<form method="post" action="{{url('saveOrder')}}">
    {{csrf_field()}}
    <div class="form-group">
      <label for="full_name" class="control-label">Full Name</label>
      <input type="text" class="form-control" id="full_name" name="full_name" placeholder="John Deer">
    </div>

    <div class="form-group">
      <label for="street_address" class="control-label">Street Address 1</label>
      <input type="text" class="form-control" id="street_address" name="street_address" placeholder="Street address, P.O. box, company name, c/o">
    </div>

    <div class="form-group">
      <label for="city" class="control-label">City</label>
      <input type="text" class="form-control" id="city" name="city" placeholder="Smallville">
    </div>

    <div class="form-group">
      <label for="zip_code" class="control-label">Zip Code</label>
      <input type="text" class="form-control" id="zip_code" name="zip_code" placeholder="#####">
    </div>

    <div class="form-group">
      <button type="submit" class="btn btn-primary">Place Order!</button>
    </div>

    </form>
@endsection

Adding routes for our application.

Open routes/web.php and add the following lines of code and save it.

&lt?php

Route::get('/', function () {
    return view('order');
});
Route::get('/index','OrderController@index');
Route::post('saveOrder','OrderController@store');

Creating migration files for the order_details table.

Run below command to create our migration

php artisan make:migration create_order_details_table

Once the migration file is created open it and add the following code.

class CreateOrderDetailsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('order_details', function (Blueprint $table) {
            $table->increments('id');
			$table->string('full_name');
			$table->string('street_address');
			$table->string('city');
			$table->string('zip_code');
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('order_details');
    }
}

Running order_details table migration.

Saving the changes and run the below command to create our table

php artisan migrate

Creating a Model file for our table.

Under the app directory create a new file named OrderDetails.php and follow lines of code.

&lt?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class OrderDetails extends Model
{
    protected $fillable = ['full_name','street_address','zip_code','city'];
}

Creating our controller to save order data.

In app/Http/Controllers directory create a new file named OrderController.php and follow lines of code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\UserDetail;

class OrderController extends Controller
{

    public function store(Request $request){

      $order = new OrderDetails([
        'full_name' => $request->get('full_name'),
        'street_address' => $request->get('street_address'),
        'city' => $request->get('city'),
        'zip_code' => $request->get('zip_code')
      ]);

      $order->save();
      return redirect('/index');
    }
    public function index(){

      $orders = OrderDetails::all();

      return view('index', compact('orders'));
    }
}

Creating a view for displaying order Data.

Create a new file named index.blade.php under resources/view/order folder and place the following code in it.

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Full Name</th>
    <th>Address</th>
    <th>City</th>
    <th>Zip Code</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($users as $user)
    <tr>
      <td>{{$user->id}}</td>
      <td>{{$user->full_name}}</td>
      <td>{{$user->street_address}}</td>
      <td>{{$user->city}}</td>
      <td>{{$user->zip_code}}</td>
	  <td><a href="{{action('UserDetailController@downloadPDF', $user->id)}}">PDF</a></td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

Creating a route for downloading files.

In the routes/web.php file add the following route.

Route::get('/downloadPDF/{id}','OrderController@downloadPDF');

Creating a pdf.blade.php file for designing our PDF.

Create a new file named pdf.blade.php under the resources/view/ folder and place the following code in it.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <table class="table table-bordered">
      <tr>
        <td>
          {{$user->full_name}}
        </td>
        <td>
          {{$user->street_address}}
        </td>
      </tr>
      <tr>
        <td>
          {{$user->city}}
        </td>
        <td>
          {{$user->zip_code}}
        </td>
      </tr>
    </table>
  </body>
</html>

Writing Function to generate and download PDF file in Controller.

Add the following code in your OrderController.php file

    public function downloadPDF($id){
      $order = OrderDetail::find($id);

      $pdf = PDF::loadView('pdf', compact('order'));
      return $pdf->download('order_invoice.pdf');

    }

That's it. Thanks for reading our post on Generating PDF in Laravel, if you face any issue and difficulties. Please let me know in the comments section.

    Please Login or Register to leave a response.

    Related Articles

    Laravel Tutorials

    Laravel 5.5 Middleware Complete Tutorial

    In Laravel, you can think middleware as a system or tool that are used to filter all HTTP requests entering your application. Middleware works between request and response of our application. It sits ..

    Laravel Tutorials

    Laravel Pagination Ajax

    Creating Ajax based pagination is Laravel 5.6. Ajax (Asynchronous JavaScript and XML) is a technique to update a specific part of webpage asynchronously without reloading the page. In this article, we..

    Laravel Tutorials

    Laravel Pagination

    According to Wikipedia Pagination is a process of separating or dividing a document or digital contents into discrete pages. In Core PHP and other frameworks, paginating record is a painful task. Lara..