Laravel QR code generation

Source Code on GitHub

I was trying to generate QR codes in Laravel and found this package simplesoftwareio/simple-qrcode and a couple of tutorials explaining how to use it shouts.dev and itsolutionstuff.com. Unfortunately, examples in the tutorials were not working well for me so I came up with the following solution.

On a Laravel project I added the QRCode package:

composer require simplesoftwareio/simple-qrcode

then, updated the config/app.php file:

'providers' => [
    ....
    SimpleSoftwareIO\QrCode\QrCodeServiceProvider::class,
],

'aliases' => [
    ....
    'QrCode' => SimpleSoftwareIO\QrCode\Facades\QrCode::class,
],

This component requires the imagick PHP extension. I found that this extension was installed in my case (MAMP 6.5 for Mac) but not enabled, so I had to edit php.ini file and remove the semi-colon in front of this line:

;extension=imagick.so

Now the component is ready to be used. The idea to demonstrate QRCodes is to create a web page accepting an ID in the URL and then displaying the QRCode of this ID. Hence, I first created a controller:

php artisan make:controller QrcodeController

and a function in this controller to accept the ID from the URL and call the respective view:

public function qrcode($id) {
    $context['id'] = $id;
    return view('qrcode/display', $context);
}

then, I created the display.blade.php view in the resources/views/qrcode folder:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <title>Laravel QR Code Example</title>
</head>
<body>

<div class="text-center" style="margin-top: 50px;">
    <h3>Laravel QRCode Example</h3>

    <img src="data:image/png;base64, {!! base64_encode(QrCode::format('png')->size(100)->generate($id)) !!} ">

    <p>ID: {{ $id }}</p>
</div>

</body>
</html>

The key point here that was causing the problem in the tutorials I found was that they were using QrCode::size() instead of QrCode::format()->size().

finally, I created the route in routes/web.php:

Route::get('qrcode/{id}', [\App\Http\Controllers\QrcodeController::class, 'qrcode']);

Now I just had to php artisan serve and then in the browser go to http://127.0.0.1:8000/qrcode/34, or any other number as the last part of the URL.

Screenshot 2021-09-10 at 12.21.47 PM.png