Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Invoice Generator Laravel Package

eslam-abass/laravel-invoice-generator

Generate customizable PDF invoices in Laravel using publishable Blade templates. Supports dynamic line items, taxes/discounts, currency and localization, optional QR code links, config-driven branding, and easy preview/PDF output via facade.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require eslam-abass/laravel-invoice-generator
    php artisan vendor:publish --provider="EslamAbass\InvoiceGenerator\InvoiceServiceProvider"
    

    This publishes the default config (config/invoice.php) and Blade template (resources/views/vendor/invoice/template.blade.php).

  2. First Use Case: Generate a basic invoice in a controller:

    use EslamAbass\InvoiceGenerator\Facades\Invoice;
    
    $invoiceData = [
        'customer' => ['name' => 'Client Co.', 'email' => 'client@example.com'],
        'items' => [['description' => 'Service', 'quantity' => 1, 'price' => 100]],
    ];
    
    $pdf = Invoice::make($invoiceData)->toPdf();
    return $pdf->stream('invoice.pdf');
    
  3. Key Files to Inspect:

    • config/invoice.php: Default settings (currency, tax rules, branding).
    • resources/views/vendor/invoice/template.blade.php: Default Blade template (customize this for branding).

Implementation Patterns

Core Workflows

  1. Data Structure: Always pass an associative array with these keys:

    $data = [
        'customer' => ['name', 'address', 'email', 'phone'], // Required
        'company' => ['name', 'address', 'logo_path'],       // Optional (uses config defaults if omitted)
        'items' => [                                      // Array of items
            ['description', 'quantity', 'price', 'tax_rate' => 0],
        ],
        'notes' => 'Optional notes',                      // Optional
        'qr_code_url' => 'https://example.com/invoice/1',  // Optional
    ];
    
  2. Generating Invoices:

    • Basic PDF:
      Invoice::make($data)->toPdf()->stream('invoice.pdf');
      
    • Preview in Browser:
      Invoice::make($data)->preview();
      
    • Save to Storage:
      $path = Invoice::make($data)->save('invoices/invoice_' . time() . '.pdf');
      
  3. Dynamic Data: Use Blade directives in the template to dynamically render data:

    @foreach($invoice->items as $item)
        <tr>
            <td>{{ $item->description }}</td>
            <td>{{ $item->quantity }}</td>
            <td>{{ number_format($item->price, 2) }}</td>
        </tr>
    @endforeach
    
  4. Multi-Language Support: Pass a locale key in the data array or set it globally in the config:

    $data = ['locale' => 'ar', ...];
    // or in config/invoice.php: 'default_locale' => 'ar'
    
  5. Tax and Discounts: Define tax rules in config/invoice.php:

    'tax_rules' => [
        'default' => 10, // 10% tax
        'special' => 5,  // Custom tax rate
    ],
    

    Apply discounts in the data:

    $data = [
        'discount' => 5, // 5% discount
        'items' => [...],
    ];
    
  6. QR Codes: Enable via config:

    'qr_code' => [
        'enabled' => true,
        'logo_path' => 'path/to/logo.png',
    ],
    

    Pass a URL in the data:

    $data = ['qr_code_url' => 'https://app.example.com/invoices/123'];
    

Integration Tips

  • Laravel Mail: Attach the PDF to an email:

    Mail::send([], [], function ($message) use ($pdf) {
        $message->subject('Your Invoice');
        $message->attach($pdf->getPath(), ['as' => 'invoice.pdf']);
    });
    
  • Laravel Storage: Save invoices to disk:

    $path = Invoice::make($data)->save('invoices/' . $invoiceId . '.pdf');
    
  • API Responses: Return the PDF as a downloadable file:

    return Invoice::make($data)->toPdf()->download('invoice.pdf');
    
  • Custom Templates: Create a new Blade template in resources/views/invoices/custom.blade.php and specify it:

    Invoice::make($data)->setTemplate('invoices.custom')->toPdf();
    

Gotchas and Tips

Pitfalls

  1. Template Paths:

    • If customizing the template, ensure the path is correct relative to resources/views/.
    • The default template is published to resources/views/vendor/invoice/template.blade.php. Override this by publishing a custom template first.
  2. Logo Paths:

    • Logo paths in the config or data must be absolute paths (e.g., storage/app/public/logos/company.png) or relative to the public folder (e.g., logos/company.png). Use public_path() in your code to resolve paths:
      $data['company']['logo_path'] = public_path('logos/company.png');
      
  3. Currency Formatting:

    • The package uses PHP’s number_format() under the hood. For non-standard formatting (e.g., commas vs. spaces), override the formatCurrency() method in a custom service provider or extend the package.
  4. QR Code Generation:

    • Requires the endroid/qr-code package. If missing, install it manually:
      composer require endroid/qr-code
      
    • Disable QR codes in the config if not needed to avoid dependency bloat.
  5. Tax Calculations:

    • Taxes are applied per-item unless a tax_rate is specified. For complex tax rules (e.g., VAT tiers), extend the TaxCalculator class or override the calculateTax() method.
  6. Locale Conflicts:

    • Ensure the locale key in the data matches a valid locale supported by PHP’s intl extension. Test with:
      setlocale(LC_ALL, $data['locale']);
      

Debugging

  1. Preview Before PDF: Use the preview() method to debug the Blade template in the browser:

    Invoice::make($data)->preview();
    
  2. Log Data: Add a temporary debug step to log the data being passed:

    \Log::info('Invoice Data', $data);
    
  3. Check Published Files: Verify the config and template were published correctly:

    php artisan vendor:publish --tag=invoice-config
    php artisan vendor:publish --tag=invoice-views
    

Extension Points

  1. Custom Invoice Class: Extend the base Invoice class to add methods:

    namespace App\Services;
    
    use EslamAbass\InvoiceGenerator\Invoice as BaseInvoice;
    
    class CustomInvoice extends BaseInvoice {
        public function addFooter($text) {
            $this->data['footer'] = $text;
            return $this;
        }
    }
    

    Bind it in a service provider:

    $this->app->bind('invoice', function () {
        return new CustomInvoice();
    });
    
  2. Override Tax Logic: Publish the config and extend the tax_rules array:

    'tax_rules' => [
        'default' => 10,
        'books' => 5, // Custom tax rate for books
    ],
    

    Then modify the template to apply per-item tax rates:

    @foreach($invoice->items as $item)
        <td>{{ $item->tax_rate }}%</td>
    @endforeach
    
  3. Add Custom Fields: Extend the data structure and template:

    $data = [
        'customer' => [...],
        'custom_fields' => ['due_date' => '2023-12-31'],
    ];
    

    Add to the template:

    @if(isset($invoice->custom_fields->due_date))
        Due Date: {{ $invoice->custom_fields->due_date }}
    @endif
    
  4. Hooks for Post-Generation: Use Laravel’s events to act after invoice generation. Extend the package to dispatch events:

    // In a service provider
    Invoice::make($data)->toPdf()->save($path);
    event(new InvoiceGenerated($data, $path));
    

Performance Tips

  1. Cache Templates: If generating many invoices, cache the compiled Blade template:

    Invoice::make($data)->setTemplate('invoices.custom')->cacheTemplate()->toPdf();
    
  2. Batch Processing: For bulk invoices, queue the generation:

    Invoice::make($data)->toPdf()->queue(function ($pdf) {
        $pdf->save("invoices/{$invoiceId}.pdf");
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope