In this post, you'll learn how to implement a simple QR Code generator for your Laravel application. We'll be using simple-qrcode package by simplesoftwareio. The implementation is very simple and straight forward so let's get started.
Let's start by installing the dependencies, run the composer command below.
Install Dependencies
Let's start by installing the dependencies, run the composer command below.
composer require simplesoftwareio/simple-qrcode "~4"
Define the Facade
Next, to easily reference the QrCode instance, let's define the facade inside "app/config.php" as follows.
# app/config.php return [ # all other configs here 'alias' => [ # all other configs here 'QrCode' => 'SimpleSoftwareIO\QrCode\Facades\QrCode', ] ];
Generate QR Code
To generate the QR Code add a new route and call in the QrCode instance and chain it with the "size" and "generate" method. The code example below will create the QR code with a size 120 and generate it with the postsrc.com link as the value.
Route::get('/qr-code', function () { return \QrCode::size(120) ->generate('https://postsrc.com'); });
Now when you visit the "/qr-code" path you will see the QR Code like below.
By right you should create a dedicated QR Code controller as necessary for your application. Depending on what's the use case of the QR Code, you should structure it as necessary.
To generate the QR Code into a different format, call the "format" method and pass in any of the picture formats below. Do note that the "png" will require the Imagick extension and if you have not installed it, do give this tutorial a read How to install Imagick on MacOS system.
By right you should create a dedicated QR Code controller as necessary for your application. Depending on what's the use case of the QR Code, you should structure it as necessary.
Generate Into Different Format
To generate the QR Code into a different format, call the "format" method and pass in any of the picture formats below. Do note that the "png" will require the Imagick extension and if you have not installed it, do give this tutorial a read How to install Imagick on MacOS system.
QrCode::format('png'); //Will return a png image QrCode::format('eps'); //Will return a eps image QrCode::format('svg'); //Will return a svg image
Generally, if you are generating it with a format, you will have to right away save it to the filesystem so if you just return it to the browser, the browser won't be able to read it unless the image format is set with "data:image/png;base64" encoding.
<img src="data:image/png;base64, {!! base64_encode(QrCode::format('png')->size(120)->generate('https://postsrc.com')) !!} ">
Customize QR Code
If you prefer to customize the QR Code appearance, you can call several of the provided methods by the package. Below are some examples of the available methods.
\QrCode::size(120) ->backgroundColor(255, 255, 255) ->color(52, 152, 219) ->style('dot') ->eye('circle') ->generate('https://postsrc.com');
Leave a reply