How to generate an invoice pdf in laravel using LaravelDaily/laravel-invoices

Invoicing is a critical aspect of any business. In Laravel, the LaravelDaily/laravel-invoices package is a fantastic tool for generating professional invoices. This package makes it simple to create and send PDF invoices. Laravel makes it simple to send email with attachments.

In this tutorial, we’ll go over how to generate an invoice PDF in Laravel utilizing LaravelDaily/laravel-invoices and send it via email.

Step 1: Laravel Project Setup

To get started with Laravel, ensure that your system has PHP and Composer installed. Then, create a new Laravel project using the following command:

composer create-project --prefer-dist laravel/laravel laravel-invoice-email

Step 2: Installing LaravelDaily/laravel-invoices Package

To create a PDF invoice in Laravel, we’ll utilize the LaravelDaily/laravel-invoices package. To download the package, open your terminal and run the following command:

composer require "laraveldaily/laravel-invoices"

Step 3: Configure the Database

Next, we’ll need to set up our database credentials in the .env file. Open the .env file and modify the following lines with your database details:

DB_HOST=localhostDB_PORT=3306DB_DATABASE=your_database_nameDB_USERNAME=your_database_userDB_PASSWORD=your_database_password

Step 4: Create the Invoice Model

We’ll now create a new model to handle invoices. Run the following command to create the Invoice model:

php artisan make:model Invoice

After that, we’ll create a migration file to generate the invoices table in the database using the following command:

php artisan make:migration create_invoices_table --create=invoices

Add the following fields to the newly generated migration file:

public function up(){    Schema::create('invoices', function (Blueprint $table) {        $table->id();        $table->string('invoice_number');        $table->string('client_name');        $table->date('invoice_date');        $table->date('due_date');        $table->decimal('total_amount', 8, 2);        $table->timestamps();    });}public function down(){    Schema::dropIfExists('invoices');}

Finally, run the migration to create the invoices table in the database using the following command:

php artisan migrate

Step 5: Create the Invoice Controller

Now we’ll generate a new controller to handle invoice creation and emailing. Run the following command to create the controller:

php artisan make:controller InvoiceController

After that, open the InvoiceController file located at app/Http/Controllers/InvoiceController.php and add the following methods:

public function create(){    return view('invoices.create');}public function store(Request $request){    $invoice = new Invoice();    $invoice->invoice_number = 'INV-'.str_pad($request->input('invoice_number'), 4, '0', STR_PAD_LEFT);    $invoice->client_name = $request->input('client_name');    $invoice->invoice_date = $request->input('invoice_date');    $invoice->due_date = $request->input('due_date');    $invoice->total_amount = $request->input('total_amount');    $invoice->save();    $pdf = \PDF::loadView('invoices.pdf', compact('invoice'));    $pdf->save(storage_path().'/app/public/invoices/'.$invoice->id.'.pdf');    $details = [        'title' => 'Invoice',        'body' => 'Please find attached invoice.',        'invoice' => $invoice	];	$to_email = $request->input('client_email');	$invoice_pdf = storage_path().'/app/public/invoices/'.$invoice->id.'.pdf';	Mail::send('emails.invoice', $details, function($message) use ($to_email, $invoice_pdf) {		$message->to($to_email)->subject('Invoice');		$message->attach($invoice_pdf);	});	return redirect('/invoices')->with('success', 'Invoice created and emailed successfully!');}

In the create() method, we return a view where the user can enter the invoice details. The store() method creates the invoice record in the database, generates a PDF invoice using the LaravelDaily/laravel-invoices package, saves the PDF to the server, and sends the PDF invoice via email.

Step 6: Create the Routes

To access the InvoiceController methods, we’ll need to create some routes. Add the following code to the routes/web.php file:

Route::get('/invoices/create', [InvoiceController::class, 'create'])->name('invoices.create');Route::post('/invoices/store', [InvoiceController::class, 'store'])->name('invoices.store');

Step 7: Create the Views

We’ll now create the views for our invoice creation and email sending. Create a new folder called invoices in the resources/views directory. Then, create two new files: create.blade.php and pdf.blade.php.

In create.blade.php, add the following HTML code:

<h1>Create Invoice</h1>@if(Session::has('success'))    <div class="alert alert-success">{{ Session::get('success') }}</div>@endif<form action="{{ route('invoices.store') }}" method="POST">    @csrf    <div class="form-group">        <label for="invoice_number">Invoice Number:</label>        <input type="number" name="invoice_number" id="invoice_number" class="form-control">    </div>    <div class="form-group">        <label for="client_name">Client Name:</label>        <input type="text" name="client_name" id="client_name" class="form-control">    </div>    <div class="form-group">        <label for="client_email">Client Email:</label>        <input type="email" name="client_email" id="client_email" class="form-control">    </div>    <div class="form-group">        <label for="invoice_date">Invoice Date:</label>        <input type="date" name="invoice_date" id="invoice_date" class="form-control">    </div>    <div class="form-group">        <label for="due_date">Due Date:</label>        <input type="date" name="due_date" id="due_date" class="form-control">    </div>    <div class="form-group">        <label for="total_amount">Total Amount:</label>        <input type="number" name="total_amount" id="total_amount" class="form-control">    </div>    <button type="submit" class="btn btn-primary">Create and Email Invoice</button></form>

In pdf.blade.php, add the following code:

<!DOCTYPE html><html><head>    <title>Invoice</title>    <style>        table {            border-collapse: collapse;            width: 100%;        }        td, th {            border: 1px solid #dddddd;            text-align: left;            padding: 8px;        }        tr:nth-child(even) {            background-color: #dddddd;        }        .invoice-container {            width: 800px;            margin: 0 auto;            font-size: 16px;            line-height: 1.5;        }        .invoice-header {            display: flex;            justify-content: space-between;            align-items: center;            margin-bottom: 20px;        }        .invoice-logo img {            height: 80px;        }        .invoice-number {            font-size: 28px;            font-weight: bold;        }        .invoice-info {            margin-left: auto;            text-align: right;        }        .invoice-info p {            margin: 0;            line-height: 1.5;        }        .invoice-info .invoice-date {            font-weight: bold;        }        .invoice-billing {            display: flex;            margin-bottom: 30px;        }        .invoice-billing .billing-details {            flex: 1;        }        .invoice-billing .billing-details h2 {            font-size: 24px;            margin-top: 0;            margin-bottom: 10px;        }        .invoice-billing .billing-details p {            margin: 0;            line-height: 1.5;        }        .invoice-billing .billing-details .client-name {            font-weight: bold;        }        .invoice-billing .billing-details .client-email {            color: #666666;        }        .invoice-billing .billing-details .invoice-dates {            margin-top: 20px;            font-weight: bold;        }        .invoice-billing .billing-details .invoice-dates p {            margin: 0;            line-height: 1.5;        }        .invoice-billing .billing-details .invoice-dates .invoice-date-label {            font-weight: normal;        }        .invoice-billing .billing-details .invoice-dates .invoice-date-value {            font-weight: bold;        }        .invoice-items {            margin-bottom: 30px;        }        .invoice-items table {            margin-top: 20px;        }        .invoice-items table th {            background-color: #f2f2f2;            font-weight: bold;        }        .invoice-items table td {            text-align: right;        }        .invoice-total {            display: flex;            justify-content: flex-end;            align-items: center;        }        .invoice-total p {            margin: 0;            line-height: 1.5;        }        .invoice-total .total-label {            font-weight: bold;            margin-right: 20px;        }        .invoice-total .total-value {            font-size: 24px;            font-weight: bold;        }    </style></head><body>    <div class="invoice-container">        <div class="invoice-header">            <div class="invoice-logo">                <img src="{{ public_path('images/logo.png') }}" alt="Logo">            </div>            <div class="invoice-number">                Invoice #{{ $invoice->invoice_number }}            </div>            <div class="invoice-info">                <p class="invoice-date">{{ $invoice->created_at->format('M d, Y') }}</p>	<p>Payment Due: {{ $invoice->due_date->format('M d, Y') }}</p>	</div></div>    <div class="invoice-billing">        <div class="billing-details">            <h2>Billing Details</h2>            <p class="client-name">{{ $invoice->customer->name }}</p>            <p class="client-email">{{ $invoice->customer->email }}</p>            <div class="invoice-dates">                <p><span class="invoice-date-label">Invoice Date:</span> <span class="invoice-date-value">{{ $invoice->created_at->format('M d, Y') }}</span></p>                <p><span class="invoice-date-label">Payment Due:</span> <span class="invoice-date-value">{{ $invoice->due_date->format('M d, Y') }}</span></p>            </div>        </div>        <div class="billing-address">            <h2>Billing Address</h2>            <p>{{ $invoice->customer->address }}</p>            <p>{{ $invoice->customer->city }}, {{ $invoice->customer->state }} {{ $invoice->customer->zip }}</p>            <p>{{ $invoice->customer->country }}</p>        </div>    </div>    <div class="invoice-items">        <table>            <thead>                <tr>                    <th>Description</th>                    <th>Quantity</th>                    <th>Price</th>                    <th>Total</th>                </tr>            </thead>            <tbody>                @foreach ($invoice->items as $item)                    <tr>                        <td>{{ $item->description }}</td>                        <td>{{ $item->quantity }}</td>                        <td>${{ number_format($item->price, 2) }}</td>                        <td>${{ number_format($item->total, 2) }}</td>                    </tr>                @endforeach            </tbody>        </table>    </div>    <div class="invoice-total">        <p class="total-label">Total:</p>        <p class="total-value">${{ number_format($invoice->total, 2) }}</p>    </div></div></body></html>

In the style section, we define the styles for various parts of the invoice, such as the table, header, billing details, and total section.

We start by creating a div container for the invoice with a width of 800 pixels and a font size of 16 pixels. We also set the line-height to 1.5.

The header section contains the company logo, invoice number, and invoice date. We use flexbox to align these elements and set the logo height to 80 pixels.

The billing details section includes the customer name, email, address, and payment due date. We also display the invoice date and payment due date.

The billing address section displays the customer’s address, city, state, zip code, and country.

The invoice items section includes a table with the item description, quantity, price, and total.

Finally, the total section displays the invoice total.

Once we have our invoice view set up, we can generate the PDF using the LaravelDaily/laravel-invoices package.

Conclusion

In conclusion, generating an invoice PDF in Laravel using the LaravelDaily/laravel-invoices package and sending it via email is a straightforward process. With the package’s pre-built templates and customization options, we can quickly generate professional-looking invoices that meet our specific needs. By following the step-by-step guide outlined in this article, we can generate invoices in a matter of minutes and send them to our clients with ease. This approach not only saves time and effort but also ensures that our invoices are accurate and consistent, helping to build a positive relationship with our clients.

Comments