How to Generate QR Code in Laravel with Custom Options?

laravel qr code generator

QR codes enhance user experiences by making interactions seamless, whether it’s accessing websites or connecting to Wi-Fi. Laravel offers an easy way to generate and customize these QR codes, letting developers adjust size and colors and even add logos.

In this blog, we’ll start with a prerequisite and learn how you can generate QR codes in Laravel. We’ll also learn about various customization options and how Laravel development experts implement them.

Additionally, we’ll dive into different types of QR codes, such as URLs, SMS, and Wi-Fi codes. So, let’s begin with the prerequisites that we need before moving to generating a QR code.

Prerequisites for Generating QR Codes in Laravel 11

Before you begin generating QR codes in Laravel 11, ensure that you have the following prerequisites in place:

  • Laravel 11 Installation: A running project set up on your local machine or server. Laravel 11 requires PHP 8.2 or later. Make sure PHP is installed and correctly configured on your machine. You can check the PHP version using the command: php -v
  • Composer: It is required to manage Laravel dependencies. Verify that Composer is installed by running the command: composer –version

With these prerequisites in place, you’ll be ready to move to the next section where we’ll begin with creating a Laravel project.

How to Generate QR Code in Laravel 11?

Generating QR code in Laravel is simple with the use of the right package. Here is a stepwise process to generate QR code using simple-qrcode package:

Step 1: Create a Laravel Project

If you don’t already have Laravel installed, you can install Laravel and create project using the following composer command:

composer create-project laravel/laravel qr-code-app

With that, our new project is created.

Step 2: Choose the QR Code Generator Package

There are two popular packages for QR code generation in Laravel:

  • chillerlan/phpqrcode: Offers a facade to create various QR code types and supports customization options like size, margin, and error correction.
  • simple-qrcode: Provides functionalities for generating QR codes with advanced customization options like color, logo integration, and more.

Choose the package that best suits your project’s needs.

Step 3: Install the Chosen Package

In this step, we’ll install the simple-qrcode package, a popular and easy-to-use QR code generator for Laravel. To install the package, run the following command in your terminal:

composer require simple-software-io/simple-qrcode

This command will download and install the simple-qrcode package and its dependencies.

Step 4: Publish the Package’s Config File

After installing the package, we need to publish its config file to configure the QR code settings. Run the following command in your terminal to publish:

php artisan vendor:publish --provider="SimpleSoftwareIO\QrCode\QrCodeServiceProvider"

Here, we published the package’s config file, which allows us to configure the QR code settings, such as the QR code size, color, and more.

Step 5: Install and Configure Imagick (Optional)

For generating high-quality PNGs, install the Imagick extension. Here is the command you can use:

sudo apt-get install php-imagick

If you are using macOS (Homebrew) you need to use the following commands:

brew install imagemagick
brew install php@8.3-imagick

After installation, ensure imagick is enabled in your php.ini. Restart the server with:

php artisan serve

With Imagick installed, PNG generation will have better quality and performance.

Step 6: Generate a QR Code

Create a controller to manage QR code generation. Run the following Artisan command:

php artisan make:controller QRCodeController

Open the newly created controller file located at app/Http/Controllers/QRCodeController.php and add the following code:

namespace App\Http\Controllers;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
class QRCodeController extends Controller
{
    public function generate()
    {
        $qr = QrCode::format('png')
                    ->size(300)
                    ->generate('https://example.com');
        return response($qr)->header('Content-Type', 'image/png');
    }
}

The controller is now configured to generate and display a QR code. Here is a brief explanation for better understanding of code:

  • format(‘png’): Specifies the output format.
  • size(300): Sets the size of the QR code.
  • generate(): Generates the QR code with the specified content.
  • response(): Sends the QR code image as a response.

Step 7: Define a Route

Define a route to access the QR code generator. Open routes/web.php and add the following route:

use App\Http\Controllers\QRCodeController;
Route::get('/generate-qr', [QRCodeController::class, 'generate']);

This route allows you to generate the QR code by visiting /generate-qr in your browser.

Step 8: Create a Blade View

If you want to display the QR code on a webpage, create a Blade view

(e.g., resources/views/qrcode.blade.php):

<!DOCTYPE html>
<html>
<head>
    <title>QR Code</title>
</head>
<body>
    {!! QrCode::size(300)->generate('https://example.com') !!}
</body>
</html>

Then adjust the route by adding the following line to routes/web.php file:

Route::get('/qr-code', [QRCodeController::class, 'generate'])->name('qr-code');

Now, the QR code is embedded within an HTML page.

Step 9: Optional Customizations

You can add logos, colors, or adjust the style of the QR code:

QrCode::format('png')
    ->size(300)
    ->color(0, 0, 0)  // Black QR code
    ->merge('public/logo.png', 0.3)  // Add a logo
    ->generate('https://example.com');

This code customizes the QR code’s size, color, and includes a logo.

Step 10: Testing the Website

Start your Laravel development server and access the QR code generation route. Here is the command you can use:

php artisan serve

Then go to http://127.0.0.1:8000/generate-qr in your browser. Your browser will display a QR code generated by Laravel.

With that we have completed the process of generating QR code in Laravel with a basic customization. Now let’s dive into how professional Laravel developers create customized QR for various needs and preferences.

Struggling to build a customized Laravel website?

Customizing the Generated QR Code

You can customize the QR code in Laravel by adjusting size, adding colors, and even adding logos. Below are various customizations that can help you enhance the look and feel of QR code:

Adjust the Size and Format

You can specify the output format and size to meet your needs.

QrCode::format('png')
      ->size(400)  // Size of the QR code
      ->generate('https://example.com');
  • format(‘png’): Sets the output format (supports PNG, SVG, etc.).
  • size(400): Increases the QR code dimensions to 400×400 pixels.

The size ensures the QR code is readable across devices, while format compatibility matters for integration in different platforms.

Add Colors to the QR Code

Make your QR codes more visually appealing by adding colors.

QrCode::format('png')
      ->size(300)
      ->color(255, 0, 0)  // Red QR code
      ->backgroundColor(255, 255, 255)  // White background
      ->generate('https://example.com');
  • color(255, 0, 0): Sets the foreground to red (RGB format).
  • backgroundColor(255, 255, 255): Sets a white background.

Note: Not all QR code scanners handle colored codes well, so testing across devices is recommended.

Adding a Logo

You can merge a logo or any image within the QR code to reflect branding.

QrCode::format('png')
      ->size(300)
      ->merge('public/logo.png', 0.3)  // 30% size logo in the center
      ->generate('https://example.com');
  • merge(): Adds a logo or image.
  • Second parameter (0.3): Controls the size of the embedded image relative to the QR code.

Use transparent logos for better readability and test the generated codes for scanning accuracy.

Add Margins to the QR Code

Control the padding around the code for enhancing the looks of the QR code:

QrCode::format('png')
      ->size(300)
      ->margin(10)  // Adds 10 units of margin
      ->generate('https://example.com');

Here, the margin() function increases the whitespace around the QR code, making it more scannable.

Generating QR Code in Blade View

You can generate and display the QR code directly in a Blade view file. Here is the code example:

<div>
    {!! QrCode::size(256)->generate('https://google.com') !!}
</div>

Or, if you need more customization you can use the following code:

<div>
    {!! QrCode::size(256)->color(255, 0, 0)->backgroundColor(255, 255, 255)->margin(1)->generate('https://google.com') !!}
</div>

This approach allows you to customize the QR code directly within your view.

Generate a QR Code with Error Correction

Error correction improves the scannability of the QR code even if part of it is blurry. Here is the code to generate such kind of QR code in Laravel:

QrCode::format('png')
      ->size(300)
      ->errorCorrection('H')  // Highest level of error correction
      ->generate('https://example.com');

Here, the errorCorrection(‘H’) ensures that up to 30% of the QR code can be damaged and still be scannable. Other levels include Q, M, and L. Here is in brief about them:

LevelValueBytes that can be restored
HighH30%
QuartileQ25%
MediumM15%
LowL7%

With that we have looked over various customizations that you can perform on QR code. Now let’s see a complete example of a QR code with almost all customization applied.

Example of a Customized and Downloadable QR Code

You can use the below code directly to customize your QR code with the necessary changes as per your need and preference. Here is the code you can add to app/Http/Controllers/QrCodeController.php for applying the customization:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
class QrCodeController extends Controller
{
    public function show()
    {
        $qrCode = QrCode::size(300)
            ->backgroundColor(255, 255, 0)
            ->color(0, 0, 255)
            ->margin(2)
            ->style('round')
            ->eye('circle')
            ->errorCorrection('H')
            ->format('png')
            ->merge(public_path('logo.png'), 0.3, true)
            ->generate('https://example.com');
        return view('qrcode', compact('qrCode'));
    }
}

To add the download option for the code generated here is the code you can add to your controller file. Add the following code to the QrCodeController class in the app/Http/Controllers/QrCodeController.php file:

public function download()
    {
        $qrCode = QrCode::size(300)
            ->backgroundColor(255, 255, 0)
            ->color(0, 0, 255)
            ->margin(2)
            ->style('round')
            ->eye('circle')
            ->errorCorrection('H')
            ->format('png')
            ->merge(public_path('logo.png'), 0.3, true)
            ->generate('https://example.com');
        return response($qrCode)
            ->header('Content-Type', 'image/png')
            ->header('Content-Disposition', 'attachment; filename="qrcode.png"');
    }

After that, add the routes in routes/web.php:

use App\Http\Controllers\QrCodeController;
Route::get('/qrcode', [QrCodeController::class, 'show']); //displays the customized QR code
Route::get('/qrcode/download', [QrCodeController::class, 'download']); //allows users to download the QR code

Create a view file resources/views/qrcode.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom QR Code</title>
</head>
<body>
    <h1>Custom QR Code</h1>
    <div>
        {!! $qrCode !!}
    </div>
    <br>
    <a href="{{ url('/qrcode/download') }}" download>Download QR Code</a>
</body>
</html>

Remember to adjust the logo path and encoded content as needed for your specific use case. Also, ensure that you have the simple-qrcode package installed with proper set up in your Laravel project. If you want to build a site with interactive and customized features consider getting in touch with our Laravel development company.

Types of QR Code in Laravel

QR codes come in various types, each serving a specific use case. Below is an overview of different QR code types, along with code examples to create them using Laravel and the SimpleSoftwareIO\QrCode package:

URL

It is the most common type of QR code, which redirects the user to a website URL when scanned. It’s widely used for marketing campaigns or sharing websites quickly.

Code:

QrCode::format('png')
      ->size(300)
      ->generate('https://example.com');

Text

Displays plain text upon scanning. Useful for sharing brief messages, discount codes, or simple instructions without requiring internet access.

Code:

QrCode::format('png')
      ->size(300)
      ->generate('Hello, welcome to our service!');

Email

Opens the default email app with pre-filled recipient, subject, and body fields. Ideal for automating communication with users.

Code:

QrCode::format('png')
      ->size(300)
      ->generate('mailto:info@example.com?subject=Inquiry&body=Please provide more details.');

Phone

When scanned, it opens the phone’s dialer with the specified number. This type of QR code is convenient for customer service and support lines.

Code:

QrCode::format('png')
      ->size(300)
      ->generate('tel:+1234567890');

SMS

This type of QR code encodes an SMS message, including the recipient’s phone number and the message content. When scanned, it pre-populates the SMS app with the details, allowing users to send the message with a single tap.

Code:

QrCode::format('png')
      ->size(300)
      ->generate('sms:+1234567890?body=Hello, I need more information.');

Wi-Fi

This code allows users to connect to a Wi-Fi network without manually entering the SSID and password. It’s perfect for events or public places like cafés.

Code:

QrCode::format('png')
      ->size(300)
      ->generate('WIFI:T:WPA;S:NetworkName;P:password123;');

Explanation: T:WPA is the network type, S is the SSID, and P is the password.

Geolocation

Opens the location on a map application. Useful for events, tourism, or guiding customers to physical stores.

Code:

QrCode::format('png')
      ->size(300)
      ->generate('geo:37.7749,-122.4194');

Explanation: The coordinates (latitude (37.7749) and longitude (,-122.4194)) are used to specify the location.

VCard (Contact Information)

Stores contact information like name, phone number, email, and address. It adds the contact directly to the user’s phonebook upon scanning.

Code:

QrCode::format('png')
      ->size(300)
      ->generate('BEGIN:VCARD
VERSION:3.0
FN:John Doe
TEL:+1234567890
EMAIL:john@example.com
END:VCARD');

Each type of QR code serves a unique purpose, ranging from sharing URLs to managing contact information. These codes are easy to generate with Laravel, offering versatility for personal, business, or event-based websites. If you are looking to build a site for your business, consider hiring Laravel developers.

Want expert assistance with your Laravel project?

FAQs About Generating QR code in Laravel

Can I integrate QR code generation into my Laravel views and APIs?
Yes, you can integrate QR code generation into your Laravel views and APIs. In your view, you can generate the QR code and display it as an image. In your APIs, you can generate the QR code and return it as an image response.
What is the difference between static and dynamic QR codes?
A static QR code contains fixed information that cannot be changed. A dynamic QR code allows you to update the content or URL behind it without changing the code itself.
Can one QR code have two links?
A QR code can only store one link at a time. However, you can work around this by using a redirect URL or a landing page that offers multiple options. For example, a QR code can direct users to a page that contains multiple links or redirects based on user selection.

Wrapping Up

Generating QR codes in Laravel simplifies user interactions, making them ideal for various applications. By using simple-qrcode package you can generate QR code in Laravel easily.

You can generate a simple QR code by configuring the chosen package and defining the route along with creating a Blade view. Once created, you can perform various customizations, such as adding a logo, colors, and more. Based on your requirements, you can use different types of QR codes such as URL, Wi-Fi, Email, and SMS.

If you are looking to create a site that ensures the best user experience and is robust, hire Laravel developers.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment