How to Generate and Display Barcodes in CakePHP 5 (Step-by-Step Guide)
Learn how to generate and display barcodes in CakePHP 5 using a custom Barcode component. This step-by-step guide covers creating the component, using it in controllers, saving barcode images as PNG or JPEG, and displaying them in CakePHP views.
In this post, you will learn how to generate barcodes in your CakePHP 5 application using the Picqer PHP Barcode Generator library. The best part is that it is completely free, easy to install with Composer, and works with many barcode types like Code128, EAN, and UPC.
What is a Barcode Generator?
A barcode generator is a small piece of code or library that creates barcode images based on a given text or number. For example, if you pass 123456789, the generator creates a scannable barcode image that represents that number. These barcodes can be printed on product labels, invoices, or shown directly on the website.
Why Use Picqer Barcode Generator?
The Picqer PHP Barcode Generator is one of the simplest libraries available for PHP developers. It does not need any external dependencies or server modules like GD or Imagick to create barcodes in SVG or HTML format. You just install it using Composer and start generating barcodes immediately. For PNG or JPG images, you need either GD library or Imagick installed.
- ✅ Works with most common barcode standards (Code 128, EAN, UPC, etc.)
- ✅ Supports multiple image formats (PNG, JPG, SVG, HTML, BMP)
- ✅ Can be used in any PHP framework, including CakePHP 5
- ✅ No complex configuration or setup needed
- ✅ Can generate both inline barcodes (Base64 images) and file-based images
Step 1: Install Using Composer
Open your terminal in the CakePHP 5 project root and run this command:
composer require picqer/php-barcode-generator
After installation, you will see the library inside vendor/picqer/php-barcode-generator. You can now start using it anywhere in your CakePHP app.
Step 2: Create a Barcode Helper in CakePHP 5
To keep the code clean, it is better to create a helper that handles the barcode generation. This helper will make it easy to use the barcode in any view file.
File path: src/View/Helper/BarcodeHelper.php
<?php
declare(strict_types=1);
namespace App\View\Helper;
use Cake\View\Helper;
use Picqer\Barcode\BarcodeGeneratorPNG;
class BarcodeHelper extends Helper
{
public function render(string $code, int $type = null, int $height = 50, int $widthFactor = 2): string
{
$generator = new BarcodeGeneratorPNG();
$type = $type ?? $generator::TYPE_CODE_128;
$barcodeData = $generator->getBarcode($code, $type, $widthFactor, $height);
$base64 = base64_encode($barcodeData);
return sprintf('<img src="data:image/png;base64,%s" alt="Barcode" />', $base64);
}
}
This helper uses the PNG format and generates an inline barcode image that can be directly displayed in any HTML page.
Step 3: Load Helper in View
Open your src/View/AppView.php file and load the helper:
public function initialize(): void
{
parent::initialize();
$this->loadHelper('Barcode');
}
Step 4: Display Barcode in a CakePHP View
You can now use the helper inside any template file (for example templates/Products/view.php):
<h3>Product Barcode</h3>
<?= $this->Barcode->render('123456789') ?>
<p>Code: 123456789</p>
This will display the barcode image for 123456789 right inside your web page.

Handling Different Barcode Requirements
In many real-world applications, you may have to create barcodes for different purposes. For example, you might want to show a barcode directly on a page, save it as an image file, or generate different formats like PNG or JPG. The picqer/php-barcode-generator library is flexible enough to handle all of these cases with just small code adjustments.
1. When You Just Want to Show Barcode on Page (Runtime Only)
This is the easiest case. You don’t need to save any file — the barcode is created on the fly and shown on the screen using base64_encode. This way, it appears as an image but is never stored on the server.
<?php
use Picqer\Barcode\BarcodeGeneratorPNG;
$generator = new BarcodeGeneratorPNG();
$barcodeData = $generator->getBarcode('123456789', $generator::TYPE_CODE_128);
echo '<img src="data:image/png;base64,' . base64_encode($barcodeData) . '" />';
?>
✅ This is best for temporary display, like on invoice preview, order detail page, or admin panel. ❌ Not suitable when you need to reuse or download the barcode later.
2. When You Need to Save Barcode Image as File (PNG or JPG)
Sometimes you may want to save the barcode image physically in a folder, for example:
- For attaching it in emails
- For later download or re-use
- For storing barcode image paths in the database
In that case, you can use the same generator but write the generated image content into a file.
<?php
use Picqer\Barcode\BarcodeGeneratorPNG;
$generator = new BarcodeGeneratorPNG();
$barcodeData = $generator->getBarcode('987654321', $generator::TYPE_CODE_128);
// create unique filename
$filename = 'barcode_' . uniqid() . '.png';
$path = WWW_ROOT . 'barcodes' . DS . $filename;
// save barcode as PNG image
file_put_contents($path, $barcodeData);
echo 'Barcode saved at: ' . $path;
?>
✅ Perfect for saving barcodes permanently or sending them as attachments. 📂 Make sure you have a writable folder (like webroot/barcodes).
3. When You Need Different Image Formats (PNG or JPG)
You can easily switch between formats by changing the generator class:
BarcodeGeneratorPNG→ for PNG imagesBarcodeGeneratorJPG→ for JPG or JPEG imagesBarcodeGeneratorSVG→ for SVG format (no image library needed)BarcodeGeneratorHTML→ for plain HTML output
Example for creating a JPG file:
<?php
use Picqer\Barcode\BarcodeGeneratorJPG;
$generator = new BarcodeGeneratorJPG();
$barcodeData = $generator->getBarcode('ABC12345', $generator::TYPE_CODE_39);
$filename = 'barcode_' . uniqid() . '.jpg';
$path = WWW_ROOT . 'barcodes' . DS . $filename;
file_put_contents($path, $barcodeData);
?>
✅ Use JPG when you want smaller image size. ⚠️ Make sure your PHP has GD or Imagick enabled.
4. How to Organize It in CakePHP
Instead of writing the same logic in multiple places, you can create a simple helper class or component to handle all barcode generation tasks.
Example Component: src/Controller/Component/BarcodeComponent.php
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Picqer\Barcode\BarcodeGeneratorPNG;
use Picqer\Barcode\BarcodeGeneratorJPG;
use Picqer\Barcode\BarcodeGeneratorSVG;
class BarcodeComponent extends Component
{
public function generate($data, $type = 'png', $barcodeType = 'TYPE_CODE_128', $save = false)
{
switch ($type) {
case 'jpg':
$generator = new BarcodeGeneratorJPG();
break;
case 'svg':
$generator = new BarcodeGeneratorSVG();
break;
default:
$generator = new BarcodeGeneratorPNG();
}
$barcode = $generator->getBarcode($data, constant(get_class($generator) . '::' . $barcodeType));
if ($save) {
$filename = 'barcode_' . uniqid() . '.' . $type;
$path = WWW_ROOT . 'barcodes' . DS . $filename;
file_put_contents($path, $barcode);
return $filename;
}
return base64_encode($barcode);
}
}
?>
Then you can simply use it in any controller:
// In your controller
$barcodeBase64 = $this->Barcode->generate('123456789');
$this->set('barcodeBase64', $barcodeBase64);
In your CakePHP view file (for example, templates/Products/view.php), you can show the generated barcode image like this:
<img alt="Barcode" src="data:image/png;base64,<?= h($barcodeBase64) ?>" />
Or if you want to save it directly, then you can write below line in your Controller and It will save the Barcode image inside the webroot folder.
$filename = $this->Barcode->generate('987654321', 'png', 'TYPE_CODE_128', true);
This approach makes your code cleaner and reusable.
Common Use Cases
- eCommerce: Generate barcodes for products to print on labels.
- Inventory Management: Create barcodes for internal stock tracking.
- Invoice System: Add order reference barcodes for quick scanning.
- Retail POS: Show product barcodes for scanning at checkout.
Tips and Best Practices
- Keep one reusable component or helper for all barcode logic.
- Keep a minimum height of 40–50 pixels for easy readability.
- Use PNG for sharp display, JPG for compact storage.
- If using in PDF, prefer SVG format for sharper output.
- Use CODE_128 unless you have a specific industry requirement.
- Store the text value (original code) in your database, not the image itself.
- Always test the barcode with a scanner app before printing.
- Clean up old barcode image files periodically if you create many temporary images.
- Ensure GD or Imagick extension is enabled for image generation.
Conclusion
Adding barcode generation to your CakePHP 5 project is very easy with the Picqer PHP Barcode Generator. With just one Composer command and a small helper, you can generate high-quality barcodes in PNG or SVG format.
This setup is developer-friendly, clean, and does not require any complex dependency. Whether you are building an eCommerce system, inventory app, or POS tool — this method works perfectly.