Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Qrcode Laravel Package

chillerlan/php-qrcode

Generate and read QR codes in PHP. Supports Model 2 QR codes (versions 1–40), ECC levels L/M/Q/H, mixed encoding modes, and multiple output formats. Includes a QR code reader based on a PHP port of ZXing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chillerlan/php-qrcode
    

    Ensure PHP 8.4+ with ext-mbstring (required) and optionally ext-gd/ext-imagick for image output.

  2. First Use Case: Generate a QR code for a URL in a Laravel Blade view:

    use Chillerlan\QRCode\QRCode;
    
    // In your controller
    $qrCodeUrl = (new QRCode)->render('https://example.com', 'svg');
    
    // In Blade
    <img src="{{ $qrCodeUrl }}" alt="QR Code">
    
  3. Key Files:

    • vendor/chillerlan/php-qrcode/src/ (Core classes)
    • examples/ (GitHub repo) for advanced use cases
    • Official Docs for API reference

Implementation Patterns

Core Workflows

  1. QR Generation:

    // Basic usage
    $qr = new QRCode;
    $qr->render('data', 'png'); // Returns data URI
    
    // With options (via QROptions)
    $options = new QROptions(['outputType' => 'png', 'size' => 300]);
    $qr->render('data', $options);
    
  2. Laravel Integration:

    • Service Provider:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(QRCode::class, function () {
              return new QRCode(new QROptions(['outputType' => 'svg']));
          });
      }
      
    • Helper Function:
      // app/Helpers/qrcode.php
      if (!function_exists('generate_qr')) {
          function generate_qr(string $data, string $format = 'svg'): string
          {
              return app(QRCode::class)->render($data, $format);
          }
      }
      
  3. Dynamic QR Codes:

    • Store QR data in DB (e.g., qr_data column) and generate on-the-fly:
      $qrData = $model->qr_data;
      $qrUrl = generate_qr($qrData);
      
  4. Reading QR Codes:

    use Chillerlan\QRCode\QRReader;
    
    $reader = new QRReader;
    $result = $reader->readImage('path/to/qr.png'); // Returns decoded data
    

Advanced Patterns

  1. Custom Output Modules: Extend QROutputModule for new formats (e.g., PDF via DomPDF):

    class QRDompdf extends QROutputModule
    {
        public function render($data, $options): string
        {
            // Custom logic
        }
    }
    
  2. Error Correction: Adjust ECC levels for robustness:

    $options = new QROptions(['eccLevel' => 'H']); // High error correction
    
  3. Multi-Format Support:

    $formats = ['svg', 'png', 'jpg'];
    $qrUrls = collect($formats)->map(fn($f) => generate_qr($data, $f));
    
  4. Caching: Cache generated QR codes (e.g., Redis) to avoid reprocessing:

    $cacheKey = 'qr_'.md5($data);
    $qrUrl = cache()->remember($cacheKey, now()->addHours(1), function() use ($data) {
        return generate_qr($data);
    });
    

Gotchas and Tips

Common Pitfalls

  1. Output Format Mismatch:

    • Ensure ext-gd/ext-imagick is installed for image formats.
    • Fallback: Use svg (no extensions required) for compatibility.
  2. Data Encoding:

    • URL-encode special characters (e.g., mailto:user@example.com?subject=Hello%20World).
    • For non-ASCII (e.g., kanji), use 8-bit binary mode:
      $options = new QROptions(['encodingMode' => 'binary']);
      
  3. Reader Limitations:

    • GD/Imagick readers may fail on distorted QR codes. Prefer svg for readability.
    • Test with QRReader::readImage() in a controlled environment.
  4. Version/Size Conflicts:

    • Long data may require higher versions (1–40). Monitor warnings:
      $qr->render($data, $options);
      if ($qr->getError()) {
          // Handle "version too low" errors
      }
      

Debugging Tips

  1. Validate Data: Use QRCode::validateData() to check if data fits the QR capacity:

    if (!QRCode::validateData('long_data_here', $options)) {
        throw new \Exception('Data too long for selected options.');
    }
    
  2. Inspect Options: Dump QROptions to verify settings:

    dd($options->toArray());
    
  3. Fallback Formats: Dynamically switch formats if primary fails:

    try {
        return generate_qr($data, 'png');
    } catch (\Exception $e) {
        return generate_qr($data, 'svg');
    }
    

Extension Points

  1. Custom Error Handling: Override QRCode::render() to log errors:

    $qr = new QRCode;
    $qr->setErrorHandler(function($error) {
        Log::error("QR Generation Error: {$error}");
    });
    
  2. Hooks for Post-Processing: Use QROutputModule::postRender() to modify output (e.g., add watermarks):

    class QRCustomOutput extends QROutputModule
    {
        public function postRender($output, $options)
        {
            return $this->addWatermark($output);
        }
    }
    
  3. Performance:

    • Prefer svg for static QR codes (no image processing overhead).
    • For batch generation, use QRCode::renderMultiple():
      $qr->renderMultiple(['data1', 'data2'], 'png');
      
  4. Security:

    • Sanitize user-provided data before encoding to prevent malformed QR codes.
    • Use QROptions::setStrictMode(true) to enforce validation.

Laravel-Specific Quirks

  1. Storage Paths: Save QR codes to storage/app/qr/:

    $path = storage_path('app/qr/code_'.Str::uuid().'.png');
    file_put_contents($path, $qr->render($data, 'png'));
    
  2. Queue Jobs: Offload QR generation to queues for long-running tasks:

    GenerateQRJob::dispatch($data, $userId)->onQueue('qr');
    
  3. View Composers: Inject QR codes globally:

    // app/ViewComposers/QRComposer.php
    public function compose(View $view)
    {
        $view->with('qrUrl', generate_qr('default_data'));
    }
    
  4. API Responses: Return QR codes as attachments:

    return response()->streamDownload(
        fn() => echo $qr->render($data, 'png'),
        'qr_code.png'
    );
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation