IT & Programming

Generate and read barcode with Laravel framework

This article demonstrate how to generate a barcode and how to read the generated barcode with barcode scanner device.

Laravel barcode generation plugin

First step is to install and configure milon / barcode laravel package from github. Follow the link below to install the plugin.

https://github.com/milon/barcode

The milon / barcode package itself has good documentation. Just follow the instructions to install and configure it with your Laravel application.

Generating barcode

<?php
     echo '<img src="data:image/png,' . Milon\Barcode\DNS1D::getBarcodePNG(5, "C39", 3, 33) . '" alt=""   />';
     echo '<img src="data:image/png;base64,' . Milon\Barcode\DNS1D::getBarcodePNG(5, "C39", 3, 33) . '" alt="" />';
?>

In Laravel, we normally use {{ }} to print a value in blade template but in case of milon / barcode package, you need to use php delimiters. In above example, “5” is your database table id of a record. It can be product id or user id or any id you want to set. Print the barcode with your printer to test it with barcode scanner.

Barcode scanner keyboard setting

Every barcode scanner has different keyboard setting. If you see the above example, the C39 is French/Belgian keyboard setting for barcode scanner. You need to open user manual of your barcode scanner device and set your desired keyboard. To test the configuration of your barcode scanner device, open notepad and scan the barcode you just generated and printed. If you see correct id in notepad then we are ready for next step which is reading and processing the barcode via html form and jquery.

Reading printed barcode

In your html blade file, create an input field.

<input type="text" id="scanner" />

Then your jquery code should be like this

$(document).ready(function () {

    $('#scanner').val('');  // Input field should be empty on page load
    $('#scanner').focus();  // Input field should be focused on page load 

    $('html').on('click', function () {
        $('#scanner').focus();  // Input field should be focused again if you click anywhere
    });

    $('html').on('blur', function () {
        $('#scanner').focus();  // Input field should be focused again if you blur
    });

    $('#scanner').change(function () {

        if ($('#scanner').val() == '') {
            return;  // Do nothing if input field is empty
        }

        $.ajax({
            url: '/scan/save',
            cache: false,
            type: 'GET',
            data: {
                user_id: $('#scanner').val()
            },
            success: function (response) {
                $('#scanner').val('');
            }
        });
    });
});

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *