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

Quar Laravel Package

tuncaybahadir/quar

Quar is a Laravel QR code generator for PHP 8.2+ and Laravel 10–13. Create QR codes quickly with a fluent API: set size, colors, and eye/marker styles (square, rounded, circle, ring). Returns ready-to-render output for Blade views.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**: Add the package via Composer:
   ```bash
   composer require tuncaybahadir/quar
  1. First Usage: Generate a basic QR code in a controller or service:
    use tbQuar\Facades\Quar;
    
    $qrCode = Quar::generate('https://example.com');
    
  2. Blade Integration: Pass the generated QR code to a view:
    <div>{{ $qrCode }}</div>
    
    Output: A default black-and-white QR code with square markers.

First Use Case

Dynamic QR Codes for User Profiles

// In a UserController
public function show(User $user) {
    $qrCode = Quar::generate(route('profile.show', $user->id));
    return view('profile', compact('user', 'qrCode'));
}

Blade View:

<img src="data:image/png;base64,{{ base64_encode($qrCode) }}" alt="Profile QR">

Implementation Patterns

1. Fluent Configuration Chain

Leverage method chaining for consistent QR code styling:

$qr = Quar::size(200)
          ->eye('rounded')
          ->color('#32a852')
          ->backgroundColor('#ffffff')
          ->style('dot', 0.7)
          ->generate('user:123');

2. Conditional Logo Integration

Use Laravel's when() trait for dynamic logo addition:

$qr = Quar::format('png')
          ->margin(1)
          ->when($user->hasLogo(), function($qr) use ($user) {
              return $qr->merge(storage_path("app/logos/{$user->logo}"), 0.25);
          })
          ->size(300)
          ->generate($user->qr_data);

3. Batch Generation

Generate multiple QR codes in a loop:

$products = Product::all();
$qrCodes = collect($products)->mapWithKeys(function($product) {
    return [
        $product->id => Quar::size(150)
                 ->color('#' . $product->color_hex)
                 ->generate(route('product.show', $product))
    ];
});

4. Text Overlay Patterns

Invoice QR Codes with Metadata:

$qr = Quar::size(300)
          ->withText('Invoice #INV-2024-001')
          ->configureText(function($text) {
              $text->setPosition('top')
                   ->setFontSize(16)
                   ->setTextColor('#ffffff')
                   ->setBackgroundColor('#2c3e50')
                   ->setBackgroundOpacity(0.7);
          })
          ->generate(route('invoice.download', $invoice->id));

5. File Storage Workflow

Save and Serve QR Codes:

// Controller
public function generateAndStore(Request $request) {
    $path = storage_path('app/qr-codes/' . uniqid() . '.png');
    Quar::format('png')
        ->size(250)
        ->generate($request->data, $path);

    return response()->file($path);
}

6. API Response Integration

Return QR codes as base64 in API responses:

return response()->json([
    'qr_code' => 'data:image/png;base64,' . base64_encode(
        Quar::format('png')
            ->size(150)
            ->generate($request->payload)
    )
]);

Gotchas and Tips

Common Pitfalls

  1. Logo Merge Bug

    • Issue: Logos may appear misaligned if margin() isn't set to 1+ (package limitation).
    • Fix: Always include ->margin(1) before ->merge().
  2. Hex Color Validation

    • Issue: Invalid hex colors (e.g., #GHI) throw silent failures.
    • Fix: Validate inputs:
      if (!preg_match('/^#[a-f0-9]{6}$/i', $hexColor)) {
          throw new \InvalidArgumentException('Invalid hex color format');
      }
      
  3. Text Position Conflicts

    • Issue: Custom text may overlap QR code content.
    • Fix: Adjust padding dynamically:
      ->configureText(function($text) {
          $text->setPadding($qrSize / 10); // 10% of QR size
      })
      
  4. File System Permissions

    • Issue: storage_path() writes may fail if directories lack permissions.
    • Fix: Ensure storage/app/qr-codes is writable:
      mkdir -p storage/app/qr-codes && chmod -R 755 storage/app/qr-codes
      

Debugging Tips

  1. Inspect Generated QR Codes Use dd() to debug the raw output:

    $rawQr = Quar::generate('test')->getData();
    dd($rawQr); // Inspect the underlying BaconQrCode object
    
  2. Check for Deprecated Methods Monitor Laravel version upgrades—some Quar methods may change (e.g., eyeColorFromHex vs. eyeColor).

  3. Performance with Large Batches

    • Issue: Generating 1000+ QR codes may time out.
    • Fix: Use queue jobs:
      GenerateQrJob::dispatch($data, $path)->onQueue('qr-generation');
      

Extension Points

  1. Custom Encoders Extend the package by creating a custom encoder:

    use tbQuar\Contracts\EncoderInterface;
    
    class CustomEncoder implements EncoderInterface {
        public function encode($data) {
            // Implement custom encoding logic
            return 'custom_encoded_' . $data;
        }
    }
    

    Register via service provider:

    $this->app->bind(EncoderInterface::class, CustomEncoder::class);
    
  2. Override Default Styles Publish and modify the config:

    php artisan vendor:publish --provider="tbQuar\Providers\QuarServiceProvider"
    

    Edit config/quar.php to set defaults (e.g., default_size, default_eye_type).

  3. Add Custom Body Patterns Extend the Generate class to support additional patterns:

    // In app/Extensions/Quar/Generate.php
    public function customStyle($smoothness = 0.5) {
        $this->options['body_pattern'] = 'custom';
        $this->options['smoothness'] = $smoothness;
        return $this;
    }
    

Configuration Quirks

  1. Gradient Limits

    • Note: Gradients require 6 color values (start RGB + end RGB).
    • Example:
      ->gradient(255, 0, 0, 0, 0, 255, 'horizontal') // Red to blue
      
  2. Text Font Paths

    • Note: Custom fonts must be absolute paths (e.g., storage_path('fonts/roboto.ttf')).
    • Example:
      ->configureText(function($text) {
          $text->setFont(storage_path('fonts/roboto.ttf'));
      })
      
  3. PNG Compression

    • Range: 0 (no compression) to 9 (max compression).
    • Tradeoff: Higher values reduce file size but may degrade quality.
    • Example:
      ->setPngCompression(7) // Balanced setting
      

Pro Tips

  1. Dynamic QR Code URLs Use Laravel's URL helpers to generate time-sensitive links:

    $qr = Quar::generate(route('payment.verify', [
        'order' => $order->id,
        'token' => $order->verification_token,
        'expires' => now()->addMinutes(15)
    ]));
    
  2. QR Code Analytics Track QR scans by embedding a UTM parameter:

    $qr = Quar::generate(
        route('scan.track', [
            'utm_source' => 'email',
            'utm_medium' => 'qr_code',
            'campaign' => 'summer_sale'
        ])
    );
    
  3. Dark Mode Support Invert colors for dark themes:

    $isDarkMode = request()->user()->prefers_dark_mode;
    $qr = Quar::color($isDarkMode ? '#ffffff' : '#000000')
              ->backgroundColor($isDarkMode ? '#121212' : '#ffffff')
              ->generate($data);
    
  4. Fallback for Unsupported Browsers Provide a static fallback in Blade:

    @if(request()->wantsJson())
        {{ $
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager