Weave 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

Barcode Bundle Laravel Package

sgk/barcode-bundle

SGK Barcode Bundle brings straightforward barcode generation to Symfony/PHP projects, wrapping TCPDF barcode support so applications can render common 1D and 2D formats in templates or services. Ideal for labels, invoices, tickets, and product codes, with simple configuration and reusable integratio...

View on GitHub
Deep Wiki
Context7

Getting Started

sgk/barcode-bundle is a thin Symfony wrapper around the standalone sgk/barcode library, which in turn uses TCPDF's 1-D barcode renderers. It exists to give you a one-liner (a Twig function) that returns a barcode as a data-URI image, so you can drop it straight into an <img src="...">.

Minimal setup:

  1. composer require sgk/barcode-bundle
  2. Register the bundle. On Symfony 2/3/4 with a kernel:
    // app/AppKernel.php
    $bundles = [ /* ... */ new SGK\BarcodeBundle\SGKBarcodeBundle() ];
    
    On Symfony 4+ Flex this is usually auto-discovered into config/bundles.php.
  3. Create the config file (app/config/config.yml or config/packages/sgk_barcode.yaml):
    sgk_barcode:
        format: png          # image format for the generated data URI
        width_factor: 1      # bar width multiplier
        height_factor: 1     # bar height multiplier
        color: black
    
    The exact keys live in DependencyInjection/Configuration.php — open that file first; it is the source of truth for defaults in the version you installed.
  4. Use it. The bundle's Twig extension exposes a barcode() function:
    <img src="{{ barcode('123456789012', 'EAN13') }}" alt="barcode" />
    
    The return value is a base64 data URI, so no route, controller, or asset pipeline is needed.

First realistic use case: an order/invoice/receipt template where you need a scannable Code128 of an order number and an EAN13 of a product SKU. That is exactly the sweet spot for this bundle — small, synchronous, template-level.

Before writing any code, read two files in the vendor directory: Twig/ (the extension — confirms the function name, argument order, and defaults) and Generator/ (the class that maps the type string to a TCPDF renderer). Those two files constitute ~90% of the package's surface area.

Implementation Patterns

Pattern 1 — inline Twig data URI (default). Fastest path; good for admin back-offices and low-traffic pages. Wrap it in a Twig macro so the type/width/height are consistent across templates:

{% macro code(value, type = 'C128') %}
    <img src="{{ barcode(value, type) }}" alt="{{ value }}">
{% endmacro %}

Pattern 2 — dedicated controller endpoint. For anything user-facing or repeated, don't inline megabytes of base64 into HTML. Route /barcode/{value} through a small controller that streams the image with a long Cache-Control and an ETag derived from value+type+dimensions. Browsers and CDNs then cache it, and your HTML stays small. Keep the value in the URL restricted to [A-Za-z0-9\-]+ to avoid route-matching surprises.

Pattern 3 — pre-generate to disk. For label sheets, packing slips, or bulk exports, run a console command that loops your entities, calls the generator service directly (inject it via constructor), and writes storage/barcodes/{sku}.png. This decouples image generation from request time and lets you regenerate in bulk when you change width/height.

Pattern 4 — embed in PDFs and emails. Because the output is a plain image string, it composes well:

  • PDF (Dompdf/wkhtmltopdf): use the data URI directly in the HTML.
  • PDF (TCPDF/mPDF): skip the bundle and call TCPDF's write1DBarcode() natively — you save a decode/encode round-trip.
  • Emails: generate the PNG once and attach it inline (cid:), because many mail clients strip data: URIs.

Integration tip — inject the generator, not the Twig extension. In services and commands, autowire/get() the generator service and call it directly. Using the Twig function outside a template means spinning up the whole Twig environment, which is wasteful in a worker or a queue job.

Testing. Assert on the result, not the pixels: check that the returned string starts with data:image/png;base64, and decodes to a non-empty image. For EAN13/UPC-A, add a fixture with a known checksum so you catch silent failures when you upgrade TCPDF.

Gotchas and Tips

  • Checksums are not optional. EAN13 expects 12 digits (the 13th is computed); EAN8 expects 7; UPC-A expects 11. Feed 13 digits to EAN13 and you may get a rendered barcode with the wrong check digit, or an empty string depending on the TCPDF version. Validate the input length before calling.
  • Invalid type strings fail silently. An unrecognised type (case matters: C128 vs CODE128, C39+ vs C39PLUS) typically yields an empty result rather than an exception, so you get a broken <img> and no error. Wrap the call and assert non-empty in dev.
  • No 2-D codes. QR / DataMatrix / PDF417 are not what this bundle is for. Reach for endroid/qr-code or bacon/bacon-qr-code and keep this package to 1-D symbologies.
  • Config changes need a cache clear. sgk_barcode values are compiled into the container; editing the YAML without bin/console cache:clear (or in prod, a cache warmup) leaves you staring at unchanged output. This is the single most common "it's not working" report.
  • Width factor is a scanability knob, not a styling knob. Setting width_factor below 1 produces barcodes that look fine on screen and fail at the scanner. If a client says "our handheld won't read it", bump width factor first, then verify print DPI.
  • Escape the value. barcode() is a Twig function; a value containing &, quotes, or < will either break the call or, worse, inject into the attribute. Escape at the call site ({{ value|e('html_attr') }}) and sanitise any value coming from user input before it reaches the generator.
  • Base64 bloats responses. A single Code128 at moderate size is tens of kilobytes of base64. Inlining dozens per page is a real performance hit; switch to Pattern 2 as soon as you have more than a couple per view.
  • Dependency weight and maintenance. The library pulls in TCPDF, which is large. Check composer show sgk/barcode-bundle and the PHP constraint — recent package activity is sparse, so verify it installs cleanly on your PHP/Symfony version and pin the version in composer.json. If it becomes a liability, the migration path is easy: the underlying sgk/barcode library is usable standalone, and TCPDF's barcode classes are directly callable, so you can drop the bundle layer without rewriting templates.
  • Debugging blanks. var_dump() the raw return of the generator; if it's an empty string, the problem is always one of: unknown type, invalid data for that symbology, or a GD/extension missing from the PHP build (TCPDF's image output path). None of those surface as exceptions by default.
  • Extension point. If you need a house style (fixed dimensions, quiet zone, colour), subclass or decorate the bundle's generator service and alias it in services.yaml, rather than repeating arguments at every call site — it keeps the Twig macro trivially short and gives you one place to change later.
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.
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
cgv/localized-resource