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

Qr Code Bundle Laravel Package

endroid/qr-code-bundle

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require endroid/qr-code-bundle
    

    Register the bundle in config/bundles.php (Symfony) or ensure it auto-discovers in Laravel (via extra.bundles in composer.json if using Symfony-like structure).

  2. First Usage Generate a QR code in a Laravel controller or Blade view:

    use Endroid\QrCode\QrCode;
    use Endroid\QrCode\Writer\PngWriter;
    
    $qrCode = QrCode::create('https://example.com')
        ->setSize(300)
        ->setWriter(new PngWriter())
        ->writeFile('qr-code.png');
    

    For Laravel-specific usage, leverage the bundle's service container:

    $qrCode = $this->container->get('endroid.qr_code');
    
  3. Blade Integration

    {!! $qrCode->setText('Hello, Laravel!')->render() !!}
    

Implementation Patterns

Common Workflows

  1. Dynamic QR Codes in Controllers

    public function generateQr(Request $request)
    {
        $qrCode = QrCode::create($request->input('content'))
            ->setSize(250)
            ->setMargin(10)
            ->setEncoding('UTF-8')
            ->setErrorCorrectionLevel(QrCode::ERROR_CORRECTION_HIGH);
    
        return response()->streamDownload(
            fn() => $qrCode->writeStream(new PngWriter()),
            'qr_code.png'
        );
    }
    
  2. Storing QR Code Data in Database

    // Store as base64 in DB
    $qrCode = QrCode::create('user:123')->writeString(new PngWriter());
    $user->qr_code = base64_encode($qrCode);
    $user->save();
    
    // Retrieve and display
    echo '<img src="data:image/png;base64,' . base64_encode($user->qr_code) . '">';
    
  3. Customizing Appearance

    $qrCode = QrCode::create('https://laravel.com')
        ->setLogoPath(public_path('images/logo.png'))
        ->setLogoSize(50)
        ->setLogoMargin(10)
        ->setColor(0, 0, 0, 128); // RGBA
    
  4. Batch Generation

    $users = User::all();
    foreach ($users as $user) {
        $qrCode = QrCode::create("user:{$user->id}")
            ->setSize(200)
            ->writeFile("storage/qr_codes/{$user->id}.png");
    }
    
  5. Integration with Laravel Notifications

    use Endroid\QrCode\QrCode;
    use Endroid\QrCode\Writer\PngWriter;
    
    public function toMail($notifiable)
    {
        $qrCode = QrCode::create("verification:{$this->token}")
            ->setSize(150)
            ->writeString(new PngWriter());
    
        return (new MailMessage)
            ->line('Your QR Code:')
            ->image('data:image/png;base64,' . base64_encode($qrCode));
    }
    

Gotchas and Tips

Pitfalls

  1. File Permissions

    • Ensure storage/ and public/ directories are writable when saving QR codes to disk.
    • Debug: storage/logs/laravel.log for permission-related errors.
  2. Memory Limits

    • Large QR codes (e.g., setSize(1000)) may hit PHP's memory_limit. Adjust in .env:
      MEMORY_LIMIT=512M
      
  3. Logo Scaling Issues

    • Logos must be square (e.g., 50x50px) to avoid distortion. Use Image facade to resize:
      use Intervention\Image\Facades\Image;
      
      $logo = Image::make(public_path('logo.png'))->resize(50, 50)->encode();
      $qrCode->setLogo($logo->getEncoded());
      
  4. Encoding Problems

    • Non-ASCII text (e.g., Chinese, emojis) may fail. Explicitly set encoding:
      $qrCode->setEncoding('UTF-8');
      
  5. Caching Static QR Codes

    • Cache generated QR codes in storage/framework/cache/ or use Laravel's cache() helper to avoid regenerating identical codes.

Debugging

  • Validate Input Use QrCode::isValid() to check if content is QR-compatible:

    if (!QrCode::isValid($request->input('content'))) {
        throw new \InvalidArgumentException('Invalid QR content');
    }
    
  • Log Errors Wrap generation in a try-catch:

    try {
        $qrCode->writeFile('qr.png');
    } catch (\Endroid\QrCode\Exception\WriterException $e) {
        Log::error('QR generation failed: ' . $e->getMessage());
    }
    

Extension Points

  1. Custom Writers Extend Endroid\QrCode\Writer\WriterInterface for formats like SVG or PDF:

    class SvgWriter implements WriterInterface {
        public function write($qrCode, $resultPath) { ... }
    }
    
  2. Laravel Service Provider Bind custom configurations in AppServiceProvider:

    public function register()
    {
        $this->app->bind('endroid.qr_code.default', function () {
            return QrCode::create('default')
                ->setSize(300)
                ->setMargin(5);
        });
    }
    
  3. Middleware for QR Validation Validate QR codes in incoming requests:

    public function handle($request, Closure $next)
    {
        if ($request->has('qr_code')) {
            $qrCode = QrCode::create($request->qr_code);
            if (!$qrCode->isValid()) {
                abort(400, 'Invalid QR code');
            }
        }
        return $next($request);
    }
    
  4. Queue Jobs for Async Generation Offload heavy QR generation to queues:

    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class GenerateQrJob implements ShouldQueue
    {
        use Queueable;
    
        public function handle()
        {
            $qrCode = QrCode::create('data')->writeFile('qr.png');
        }
    }
    

Configuration Quirks

  • Bundle-Specific Settings Override default settings in config/packages/endroid_qr_code.php (Symfony) or manually in Laravel:

    config([
        'endroid_qr_code.default' => [
            'size' => 300,
            'margin' => 10,
            'encoding' => 'UTF-8',
        ],
    ]);
    
  • Environment-Specific Adjustments Use .env to toggle features:

    QR_CODE_ENABLED=true
    QR_CODE_DEFAULT_SIZE=250
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware