Dev Tips & Tricks

Easily Create QR Codes With Our QR Code Library and Laravel

Back to posts

Creating QR codes using the 2amigos/qrcode-library is as easy as instantiating a new object in PHP. Generally speaking, all we need to do is:

<?php
// ...
$qrCode = new QrCode(“Pretty new QR Code with 2amigos/qrcode-library”);
// ...
?>

<!-- displays qrcode as an image -->
<img src="<?= $qrCode->writeDataUri(); ?>"/>

In this post, we’ll explore the available settings and formats for this library, using Laravel to enhance our experience.

Let’s start by creating a new Laravel project:

$ composer create-project laravel/laravel 2am-qrcode
$ cd 2am-qrcode

Then, install the 2amigos/qrcode-library library:

$ composer require 2amigos/qrcode-library:^3.0

Before putting this library to work, let's create a controller and define the route where our samples will live:

$ php artisan make:controller QrCodeController

It will create a new controller under app/Http/Controllers, named QrCodeController.php.

On ./routes/web.php, substitute the file content for the given code:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\QrCodeController;

Route::name('qrcode')->group(function() {
    Route::get('/', [QrCodeController::class, 'index']);
});

Now we can finally put our hands on the library itself and start building some QR Codes! On our QrCodeController, create the following function:

<?php
namespace App\Http\Controllers;

use Da\QrCode\QrCode;

class Controller {
    // ....
    public function index()
    {
        $text = new QrCode('2am. technologies');

        return view('qrcode.index', [
            // set variable to be accessible through the view
            // you can define other qrcode variables we’ll be creating on this array
            'text' => $text, 
        ]);
    }
    // ...
}

The function above creates a new QR Code with simple text on it, as we did right at the beginning of this post.

With the function created, we’re missing only our view to be able to view our first QR Code.

Create a file named index.blade.php under ./resources/views/qrcode with the code below:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>{{env('APP_NAME')}}</title>
    <!-- Fonts -->
    <link rel="pre-connect" href="https://fonts.bunny.net">
    <link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
		html, body {
			background: #191a1f;
		}

		.card {
			background: #4d4f5e;
			border: 1px solid #80839a;
			color: #eee;
		}

		a, b, .card-title {
			color: #fff;
		}

		p {
			color: #eee;
		}

		a:hover {
			color: #ddd;
		}
	</style>

</head>
<body>
    <div class="container mt-5">
       <div class="row">
            <div class="card col-4">
                <div class="card-body">
                    <h5 class="card-title"> Text </h5>
                   <img src="<?= $text->writeDataUri(); ?>"/>
                </div>
            </div>

<!-- you can place other cards here for the other samples we’ll create following the sample above -->

       </div>
    </div>
</body>
</html>

There it is, we have just created the first QR Code with 2amigos/qrcode-library. Running the following command will publish the application to http://127.0.0.1:8000. Accessing it will display your brand-new QR Code.

$ php artisan serve

Digging deeper into the library, we can start exploring its functions and QR Code formats other than text.

Label

First of all, we can enhance the first example by setting a label for it. To achieve this, we must import the class Da\QrCode\Label. Check the example:

<?php

use Da\QrCode\Label;
use Da\QrCode\Contracts\LabelInterface;

$text->setLabel(new Label(
    text: '2am.tech',
    font: null,
    fontSize: 14,
    align: LabelInterface::ALIGN_RIGHT
));

On the code above we’re using the function setLabel to define a label to our generated QR Code. It receives one unique parameter, being a string or a Label object. If you define a string, the label will use the default configuration: centered, the font will be noto_sans, size 16.

There is a function setLogo to add a logo to your QR Code.
You can use the setLogoWidth function to adjust its size. Ideally, your logo size should be up to 16% of your QR Code width (rounded down).
Add an image to ./public/assets/logo.png.

<?php
$text->setSize(300)
     ->setLogo(public_path('assets/logo.png'))
     ->setLogoWidth(48);

You can change the background and foreground color by using the functions setBackgroundColor and setForegroundColor, setting RGB values as parameters:

<?php
$text
    ->setForegroundColor(
        red: 1,
        green: 149,
        blue: 240,
    )
    ->setBackgroundColor(
        red: 199,
        green: 210,
        blue: 220,
    );

It’s strongly recommended to have the foreground color darker than the background color, keeping a reasonable contrast between the colors to make it possible for the readers to detect the barcode.

Format Writers

Though the default format for generated QR Code images is png, you can easily change it by setting the writer. You can achieve it by setting the writer right on the constructor or by using the method setWriter().

<?php
use Da\QrCode\Writer\JpgWriter;
// …
$text = new QrCode(text: '2am. Technologies', writer: new JpgWriter());
// or
$text = (new QrCode('2am. Technologies'))
       ->setWriter(new JpgWriter());

The available formats are:

  • PngWriter (default)
  • JpgWriter
  • SvgWriter
  • EpsWriter

Saving Qr Code File and Resource Routes

You can easily save the file by using the method writeFile (pathname).

<?php
// ...
$text->writeFile(storage_path('app/public/text.jpg'));

To use it on a resource route, you must specify the content type and use the writeString() function.

<?php
use Da\QrCode\QrCode;

$qrCode = new QrCode('https://2am.tech');

header('Content-Type: ' . $qrCode->getContentType());

$qrCode->writeString();

We can easily create a resource route on Laravel. Update our ./routes/web.php to have the following:

<?php
Route::name('qrcode')->group(function() {
    Route::get('/', [QrCodeController::class, 'index']);
    Route::get('/resource/{content}', [QrCodeController::class, 'resource']);
});

Then, on our QrCodeController, add the method below:

<?php

class QrCodeController {
    //...
    
    public function resource(string $text)
    {
        $qrCode = new QrCode($text);

        return response($qrCode->writeString())
            ->withHeaders([
                'Content-Type' => $qrCode->getContentType()
            ]);
    }

    // ...
}

This code creates a route where we can pass a text as an attribute, then it renders a simple text QR Code. Accessing http://127.0.0.1:8000/resource/2am. Techonologies results with the following:

QR Code Formats

With the available methods covered, we can move one step forward and dive into some of the available QR formats.

To see the full list of available formats, check the [link] library docs - https://qrcode-library.readthedocs.io/en/latest/

To create a QR Code with a specific format, you must create a new format and then pass it to the QrCode constructor instead of a text string. Each format has its own specific required parameters and attributes.

BookMark Format

The bookmark format allows you to encode a URI with a title to your QR Code.

<?php
use Da\QrCode\Format\BookMarkFormat;


$bookMarkFormat = new BookMarkFormat([
            'title' => '2am. technologies',
            'url' => 'https://2am.tech',
        ]);
$bookMark = new QrCode($bookMarkFormat);

return view('qrcode.index', [
      'bookMark' => $bookMark,
      
];

On your ./resources/qrcode/index.blade.php

<div class="card col-4">
     <div class="card-body">
            <h5 class="card-title"> BookMark </h5>
            <img src="<?= $bookMark->writeDataUri(); ?>"/>
      </div>
</div>
BookMark

ICal Format

The ICal format allows you to create an appointment/event to the calendar.

<?php
use Da\QrCode\Format\ICalFormat;

$iCalFormat = new ICalFormat([
            'summary' => 'test-summary',
            'startTimestamp' => 1260232200,
            'endTimestamp' => 1260318600
        ]);
$iCal = new QrCode($iCalFormat);

return view('qrcode.index', [
           
           'iCal' => $iCal,
];

On your ./resources/qrcode/index.blade.php

…
<div class="card col-4">
     <div class="card-body">
            <h5 class="card-title"> ICal</h5>
            <img src="<?= $iCal->writeDataUri(); ?>"/>
      </div>
</div>
…

MeCard Format

This format helps share contact information.

<?php
use Da\QrCode\Format\MeCardFormat;

$meCardFormat = new MeCardFormat();
$meCardFormat->firstName = 'Antonio';
$meCardFormat->lastName = 'Ramirez';
$meCardFormat->sound = 'docomotaro';
$meCardFormat->phone = '657657XXX';
$meCardFormat->videoPhone = '657657XXX';
$meCardFormat->email = 'hola@2amigos.us';
$meCardFormat->note = 'test-note';
$meCardFormat->birthday = '19791201';
$meCardFormat->address = 'test-address';
$meCardFormat->url = 'http://2am.tech';
$meCardFormat->nickName = 'tonydspaniard';
$meCard = new QrCode($meCardFormat);

return view('qrcode.index', [
    // ... other parameters
    'meCard' => $meCard,
]);

Then on your ./resources/qrcode/index.blade.php

<div class="card col-4">
     <div class="card-body">
            <h5 class="card-title"> MeCard </h5>
            <img src="<?= $meCard->writeDataUri(); ?>"/>
      </div>
</div>

Finally, here are all the QR Codes we generated using 2amigos/qrcode-library and Laravel:

Demo

Want to see these samples and all other formats in place? You can find them on our demo repository.

Alternatively, if you prefer a live demonstration, you can access it through this link.

Share with
Terms of Use | Privacy Policy