PHP code example of finller / laravel-invoices

1. Go to this page and download the library: Download finller/laravel-invoices library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

finller / laravel-invoices example snippets


use Elegantly\Invoices\Models\Invoice;
use Elegantly\Invoices\InvoiceDiscount;
use Elegantly\Invoices\Models\InvoiceItem;
use Elegantly\Invoices\Enums\InvoiceType;

return [

    'model_invoice' => Invoice::class,
    'model_invoice_item' => InvoiceItem::class,

    'discount_class' => InvoiceDiscount::class,

    'cascade_invoice_delete_to_invoice_items' => true,

    'serial_number' => [
        /**
         * If true, will generate a serial number on creation
         * If false, you will have to set the serial_number yourself
         */
        'auto_generate' => true,

        /**
         * Define the serial number format used for each invoice type
         *
         * P: Prefix
         * S: Serie
         * M: Month
         * Y: Year
         * C: Count
         * Example: IN0012-220234
         * Repeat letter to set the length of each information
         * Examples of formats:
         * - PPYYCCCC : IN220123 (default)
         * - PPPYYCCCC : INV220123
         * - PPSSSS-YYCCCC : INV0001-220123
         * - SSSS-CCCC: 0001-0123
         * - YYCCCC: 220123
         */
        'format' => 'PPYYCCCC',

        /**
         * Define the default prefix used for each invoice type
         */
        'prefix' => [
            InvoiceType::Invoice->value => 'IN',
            InvoiceType::Quote->value => 'QO',
            InvoiceType::Credit->value => 'CR',
            InvoiceType::Proforma->value => 'PF',
        ],

    ],

    'date_format' => 'Y-m-d',

    'default_seller' => [
        'name' => null,
        'address' => [
            'street' => null,
            'city' => null,
            'postal_code' => null,
            'state' => null,
            'country' => null,
        ],
        'email' => null,
        'phone' => null,
        'tax_number' => null,
        'company_number' => null,
    ],

    /**
     * ISO 4217 currency code
     */
    'default_currency' => 'USD',

    'pdf' => [

        'paper' => [
            'size' => 'a4',
            'orientation' => 'portrait',
        ],

        /**
         * Default DOM PDF options
         *
         * @see Available options https://github.com/barryvdh/laravel-dompdf#configuration
         */
        'options' => [
            'isRemoteEnabled' => true,
            'isPhpEnabled' => false,
            'fontHeightRatio' => 1,
            /**
             * Supported values are: 'DejaVu Sans', 'Helvetica', 'Courier', 'Times', 'Symbol', 'ZapfDingbats'
             */
            'defaultFont' => 'Helvetica',

            'fontDir' => storage_path('fonts'), // advised by dompdf (https://github.com/dompdf/dompdf/pull/782)
            'fontCache' => storage_path('fonts'),
            'tempDir' => sys_get_temp_dir(),
            'chroot' => realpath(base_path()),
        ],

        /**
         * The logo displayed in the PDF
         */
        'logo' => null,

        /**
         * The template used to render the PDF
         */
        'template' => 'default.layout',

        'template_data' => [
            /**
             * The color displayed at the top of the PDF
             */
            'color' => '#050038',
        ],

    ],

];

use \Elegantly\Invoices\Pdf\PdfInvoice;
use \Elegantly\Invoices\Pdf\PdfInvoiceItem;
use \Elegantly\Invoices\Support\Seller;
use \Elegantly\Invoices\Support\Buyer;
use \Elegantly\Invoices\Support\Address;
use \Elegantly\Invoices\Support\PaymentInstruction;
use \Elegantly\Invoices\InvoiceDiscount;
use Brick\Money\Money;

$pdfInvoice = new PdfInvoice(
    name: "Invoice",
    state: "paid",
    serial_number: "INV-241200001",
    seller: new Seller(
        company: 'elegantly',
        name: 'Quentin Gabriele', // (optional)
        address: new Address(
            street: "Place de l'Opéra",
            city: 'Paris',
            postal_code: '75009',
            country: 'France',
        ),
        email: '[email protected]',
        tax_number: 'FR123456789',
        fields: [
            // Custom fields to display with the seller
            "foo" => "bar"
        ]
    ),
    buyer: new Buyer(
        company: "Doe Corporation" // (optional)
        name: 'John Doe', // (optional)
        address: new Address(
            street: '8405 Old James St.Rochester',
            city: 'New York',
            postal_code: '14609',
            state: 'NY',
            country: 'United States',
        ),
        shipping_address: new Address( // (optional)
            street: [ // multiple lines street
                '8405 Old James St.Rochester',
                'Apartment 1',
            ],
            city: 'New York',
            postal_code: '14609',
            state: 'NY',
            country: 'United States',
        ),
        email: '[email protected]',
        fields: [
            // Custom fields to display with the buyer
            "foo" => "bar"
        ]
    ),
    description: "An invoice description",
    created_at: now(),
    due_at: now(),
    paid_at: now(),
    tax_label: "VAT France (20%)",
    fields: [ // custom fields to display at the top
        'Order' => "PO0234"
    ],
    items: [
        new PdfInvoiceItem(
            label: "Laratranslate Unlimitted" ,
            unit_price: Money::of(99.0, 'USD'),
            tax_percentage: 20.0,
            quantity: 1,
            description: "Elegant All-in-One Translations Manager for Laravel",
        ),
    ],
    discounts: [
        new InvoiceDiscount(
            name: "Summer offer",
            code: "SUMMER",
            percent_off: 50,
        )
    ],
    paymentInstructions: [
        new PaymentInstruction(
            name: 'Bank Transfer',
            description: 'Make a direct bank transfer using the details below.',
            qrcode: 'data:image/png;base64,' . base64_encode(
                file_get_contents(__DIR__.'/../resources/images/qrcode.png')
            ),
            fields: [
                'Bank Name' => 'Acme Bank',
                'Account Number' => '12345678',
                'IBAN' => 'GB12ACME12345678123456',
                'SWIFT/BIC' => 'ACMEGB2L',
                'Reference' => 'INV-0032/001',
                '<a href="#">Pay online</a>',
            ],
        ),
    ],
    logo: public_path('/images/logo.png'), // local path or base64 string
    template: "default.layout", // use the default template or use your own
    templateData: [ // custom data to pass to the template
        'color' => '#050038'
    ],
);

namespace App\Http\Controllers;

use Elegantly\Invoices\Pdf\PdfInvoice;

class InvoiceController extends Controller
{
    public function showAsPdf()
    {
        $pdfInvoice = new PdfInvoice(
            // ...
        );

        return $pdfInvoice->stream();
    }
}

namespace App\Http\Controllers;

use Elegantly\Invoices\Pdf\PdfInvoice;
use Illuminate\Support\Facades\Storage;

class InvoiceController extends Controller
{
    public function store()
    {
        $pdfInvoice = new PdfInvoice(
            // ...
        );

        Storage::put(
            "path/to/{$pdfInvoice->getFilename()}",
            $pdfInvoice->getPdfOutput()
        );

        // ...
    }
}

namespace App\Http\Controllers;

use Elegantly\Invoices\Pdf\PdfInvoice;

class InvoiceController extends Controller
{
    public function download()
    {
        $pdfInvoice = new PdfInvoice(
            // ...
        );

        return $pdfInvoice->download(
            /**
             * (optional)
             * The default filename is the serial_number
             */
            filename: 'invoice.pdf'
        );
    }
}

namespace App\Http\Controllers;

use Elegantly\Invoices\Pdf\PdfInvoice;

class Invoice extends Component
{
    public function download()
    {
        $pdfInvoice = new PdfInvoice(
            // ...
        );

        return response()->streamDownload(function () use ($pdfInvoice) {
            echo $pdf->getPdfOutput();
        }, $pdf->getFilename()); // The default filename is the serial number
    }
}

namespace App\Http\Controllers;

use Elegantly\Invoices\Pdf\PdfInvoice;

class InvoiceController extends Controller
{
    public function showAsView()
    {
        $pdfInvoice = new PdfInvoice(
            // ...
        );

        return $pdfInvoice->view();
    }
}

<div class="aspect-[210/297] bg-white shadow-md">
    @

use \Elegantly\Invoices\Pdf\PdfInvoiceItem;

new PdfInvoiceItem(
    label: "Laratranslate Unlimitted" ,
    unit_price: Money::of(99.0, 'USD'),
    tax_percentage: 20.0, // a float between 0.0 and 100.0
),

use \Elegantly\Invoices\Pdf\PdfInvoiceItem;

new PdfInvoiceItem(
    label: "Laratranslate Unlimitted" ,
    unit_price: Money::of(99.0, 'USD'),
    unit_tax: Money::of(19.8, 'USD'),
),

use \Elegantly\Invoices\Pdf\PdfInvoice;
use \Elegantly\Invoices\InvoiceDiscount;
use Brick\Money\Money;

$pdfInvoice = new PdfInvoice(
    // ...
    discounts: [
        new InvoiceDiscount(
            name: "Summer offer",
            code: "SUMMER",
            percent_off: 20.0,
        )
    ],
);

use \Elegantly\Invoices\Pdf\PdfInvoice;
use \Elegantly\Invoices\InvoiceDiscount;
use Brick\Money\Money;

$pdfInvoice = new PdfInvoice(
    // ...
    discounts: [
        new InvoiceDiscount(
            name: "Summer offer",
            code: "SUMMER",
            amount_off: Money::of(20.0, 'USD'),
        )
    ],
);

use \Elegantly\Invoices\Pdf\PdfInvoice;
use \Elegantly\Invoices\Support\PaymentInstruction;

$pdfInvoice = new PdfInvoice(
    // ...
    paymentInstructions: [
        new PaymentInstruction(
            name: 'Bank Transfer',
            description: 'Make a direct bank transfer using the details below.',
            qrcode: 'data:image/png;base64,' . base64_encode(
                file_get_contents(__DIR__.'/../resources/images/qrcode.png')
            ),
            fields: [
                'Bank Name' => 'Acme Bank',
                'Account Number' => '12345678',
                'IBAN' => 'GB12ACME12345678123456',
                'SWIFT/BIC' => 'ACMEGB2L',
                'Reference' => 'INV-0032/001',
                '<a href="#">Pay online</a>',
            ],
        ),
    ]
);

return [

    // ...

    'pdf' => [

        /**
         * The template used to render the PDF
         */
        'template' => 'my-custom.layout',

        'template_data' => [
            /**
             * The color displayed at the top of the PDF
             */
            'color' => '#050038',
        ],

    ],

];

use App\Models\Team;
use App\Models\Order;

use Brick\Money\Money;
use Elegantly\Invoices\Models\Invoice;
use Elegantly\Invoices\Enums\InvoiceState;
use Elegantly\Invoices\Enums\InvoiceType;

$customer = Team::find(1);
$order = Order::find(2);

$invoice = new Invoice(
    'type'=> "invoice",
    'state'=> "paid",
    'seller_information'=> config('invoices.default_seller'),
    'buyer_information'=>[
        'company'=> "Doe Corporation" // (optional)
        'name'=> 'John Doe', // (optional)
        'address'=> [
            'street'=> '8405 Old James St.Rochester',
            'city'=> 'New York',
            'postal_code'=> '14609',
            'state'=> 'NY',
            'country'=> 'United States',
        ],
        'shipping_address'=> [ // (optional)
            'street'=> [ // multiple lines street
                '8405 Old James St.Rochester',
                'Apartment 1',
            ],
            'city'=> 'New York',
            'postal_code'=> '14609',
            'state'=> 'NY',
            'country'=> 'United States',
        ]
        'email'=> '[email protected]',
        'fields'=> [
            // Custom fields to display with the buyer
            "foo" => "bar"
        ]
    ],
    'description'=> "An invoice description",
    'due_at'=> now(),
    'paid_at'=> now(),
    'tax_type'=> "eu_VAT_FR",
    'tax_exempt'=> null,
);

// Learn more about the serial number in the next section
$invoice->configureSerialNumber(
    prefix: "ORD",
    serie: $customer->id,
    year: now()->format('Y'),
    month: now()->format('m')
)

$invoice->buyer()->associate($customer); // optionnally associate the invoice to any model
$invoice->invoiceable()->associate($order); // optionnally associate the invoice to any model

$invoice->save();

$invoice->items()->saveMany([
    new InvoiceItem([
        'label' => "Laratranslate Unlimitted",
        'description' => "Elegant All-in-One Translations Manager for Laravel",
        'unit_price' => Money::of(99.0, 'USD'),
        'tax_percentage' => 20.0,
        'quantity' => 1,
    ]),
]);

use Elegantly\Invoices\Models\Invoice;
$invoice = new Invoice();

$invoice->configureSerialNumber(
    prefix: "ORG",
    serie: $buyer_id,
);


$invoice = new Invoice();

$invoice->configureSerialNumber(
    format: "PP-SSSSSS-YYMMCCCC",
    prefix: "IN",
    serie: 100,
    year: now()->format('Y'),
    month: now()->format('m')
);

$invoice->save();

$invoice->serial_number; // IN-000100-24010001

$invoice = Invoice::first();

$pdfInvoice = $invoice->toPdfInvoice();

namespace App\Http\Controllers;

use App\Models\Invoice;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function show(Request $request, string $serial)
    {
        /** @var Invoice $invoice */
        $invoice = Invoice::where('serial_number', $serial)->firstOrFail();

        $this->authorize('view', $invoice);

        return $invoice->toPdfInvoice()->stream();
    }

    public function download(Request $request, string $serial)
    {
        /** @var Invoice $invoice */
        $invoice = Invoice::where('serial_number', $serial)->firstOrFail();

        $this->authorize('view', $invoice);

        return $invoice->toPdfInvoice()->download();
    }

    public function store(Request $request, string $serial)
    {
        /** @var Invoice $invoice */
        $invoice = Invoice::where('serial_number', $serial)->firstOrFail();

        Storage::put(
            "path/to/invoice.pdf",
            $invoice->toPdfInvoice()->getPdfOutput()
        );

        // ...
    }
}

namespace App\Mail;

use App\Models\Invoice;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class PaymentInvoice extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct(
        protected Invoice $invoice,
    ) {}


    public function attachments(): array
    {
        return [
            $this->invoice->toMailAttachment()
        ];
    }
}

namespace App\Mail;

use App\Models\Invoice;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;

class PaymentInvoice extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new message instance.
     */
    public function __construct(
        protected Invoice $invoice,
    ) {}

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->attach($this->invoice->toMailAttachment());
    }
}

namespace App\Models;

class Invoice extends \Elegantly\Invoices\Models\Invoice
{
    // ...
}

namespace App\Models;

use Elegantly\Invoices\Pdf\PdfInvoice;

class Invoice extends \Elegantly\Invoices\Models\Invoice
{
    function toPdfInvoice(): PdfInvoice
    {
        return new PdfInvoice(
            // ... your custom PdfInvoice properties and configuration
        );
    }
}

return [
    // ...

    'model_invoice' => \App\Models\Invoice::class,

    // ...
];

class PdfInvoice extends \Elegantly\Invoices\Pdf\PdfInvoice
{

    public function __construct(
        // your custom constructor
    ){
        // ...
    }

    public function getFilename(): string
    {
        return str($this->serial_number)
            ->replace(['/', '\\'], '_')
            ->append('.pdf')
            ->value();
    }
}

namespace App\Models;

use App\ValueObjects\PdfInvoice;

class Invoice extends \Elegantly\Invoices\Models\Invoice
{
    function toPdfInvoice(): PdfInvoice
    {
        return new PdfInvoice(
            // Pass any 

namespace App\Enums;

use Elegantly\Invoices\Contracts\HasLabel;

enum InvoiceType: string implements HasLabel
{
    case Invoice = 'invoice';
    case Quote = 'quote';
    case Credit = 'credit';
    case Proforma = 'proforma';

    public function getLabel(): string
    {
        return match ($this) {
            self::Invoice => __('invoices::invoice.types.invoice'),
            self::Quote => __('invoices::invoice.types.quote'),
            self::Credit => __('invoices::invoice.types.credit'),
            self::Proforma => __('invoices::invoice.types.proforma'),
        };
    }
}

namespace App\Models;

use Elegantly\Invoices\Enums\InvoiceState;
use Elegantly\Invoices\Enums\InvoiceType;

/**
 * @property InvoiceType $type
 * @property InvoiceState $state
 */
class Invoice extends \Elegantly\Invoices\Models\Invoice
{
    protected $attributes = [
        'type' => InvoiceType::Invoice->value,
        'state' => InvoiceState::Draft->value,
    ];

    protected function casts(): array
    {
        return [
            ...parent::casts(), // Merge with parent casts for other potential attributes
            'type' => InvoiceType::class,
            'state' => InvoiceState::class,
        ];
    }
}

return [
    // ...

    'model_invoice' => \App\Models\Invoice::class,

    // ...
];

namespace App\Models;

use Illuminate\Http\File;

class Invoice extends \Elegantly\Invoices\Models\Invoice
{
    public function getLogo(): ?string
    {
        $logoPath = public_path('logo.png'); // Replace with your dynamic logic

        if (!file_exists($logoPath)) {
            return null; // Or a default logo
        }

        $file = new File($logoPath);
        $mime = $file->getMimeType();
        $logoData = "data:{$mime};base64," . base64_encode(file_get_contents($logoPath)); // Use file_get_contents for raw data

        return $logoData;
    }
}

return [
    // ...

    'model_invoice' => \App\Models\Invoice::class,

    // ...
];
bash
php artisan vendor:publish --tag="invoices-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="invoices-config"
bash
php artisan vendor:publish --tag="invoices-views"
bash
php artisan vendor:publish --tag="invoices-config"
bash
php artisan vendor:publish --tag="invoices-config"
bash
php artisan vendor:publish --tag="invoices-config"