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

Phpqrcode Laravel Package

aferrandini/phpqrcode

PHP QR Code is a lightweight library to generate QR codes in pure PHP. Create PNG images from text, URLs, or other data with configurable error correction, size, and margins—ideal for adding QR generation to PHP apps without extra extensions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require aferrandini/phpqrcode
    

    (Note: Due to the package being archived, ensure compatibility with your PHP version—tested up to PHP 7.x in legacy projects.)

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

    use Aferrandini\PHPQRCode\QRCode;
    
    $qrCode = new QRCode();
    $qrCode->render('https://example.com', 'qr.png');
    

    (Outputs qr.png in the current directory.)

  3. Quick Blade Integration In a Blade template:

    <img src="{{ route('generate.qr', ['data' => 'Hello World']) }}" alt="QR Code">
    

    (Requires a route and controller to handle dynamic generation.)


First Use Case: Dynamic QR Codes for User Profiles

  1. Route Definition
    Route::get('/profile/{user}/qr', [QRController::class, 'generate'])->name('profile.qr');
    
  2. Controller Logic
    public function generate(User $user)
    {
        $qrCode = new QRCode();
        $qrCode->render(
            route('profile.show', $user),
            public_path("uploads/qr/{$user->id}.png")
        );
        return response()->file(public_path("uploads/qr/{$user->id}.png"));
    }
    
  3. Cache for Performance Store generated QR codes in storage/app/qr/ and use Laravel’s Storage facade for retrieval.

Implementation Patterns

1. Reusable QR Code Service

Create a dedicated service class to encapsulate logic:

namespace App\Services;

use Aferrandini\PHPQRCode\QRCode;

class QRCodeService {
    public function generate(string $data, string $path): void
    {
        $qrCode = new QRCode();
        $qrCode->render($data, $path);
    }

    public function getUrl(string $path): string
    {
        return Storage::url($path);
    }
}

Usage in Controller:

public function generateQR(Request $request)
{
    $service = new QRCodeService();
    $service->generate($request->data, "qr/{$request->id}.png");
    return $service->getUrl("qr/{$request->id}.png");
}

2. Customizing QR Code Appearance

Leverage the library’s built-in options:

$qrCode = new QRCode();
$qrCode->setSize(300);          // Adjust size (default: 100px)
$qrCode->setMargin(5);         // Margin around the code
$qrCode->setErrorCorrection('H'); // Error correction level (L/M/Q/H)
$qrCode->render($data, 'custom.png');

3. Batch Generation

Generate multiple QR codes in bulk (e.g., for product barcodes):

public function generateBatch(array $dataArray, string $prefix = 'qr_')
{
    foreach ($dataArray as $index => $data) {
        $qrCode = new QRCode();
        $qrCode->render($data, "batch/{$prefix}{$index}.png");
    }
}

4. Integration with Laravel Storage

Use Laravel’s Storage facade for cloud storage (S3, etc.):

use Illuminate\Support\Facades\Storage;

$qrCode->render($data, 'qr.png');
Storage::disk('s3')->put('qr-codes/qr.png', file_get_contents('qr.png'));

5. Dynamic QR Codes in API Responses

Return QR codes as base64-encoded strings in JSON:

public function getQRCodeAsBase64(string $data)
{
    ob_start();
    $qrCode = new QRCode();
    $qrCode->render($data);
    $base64 = 'data:image/png;base64,' . base64_encode(ob_get_clean());
    return response()->json(['qr_code' => $base64]);
}

Gotchas and Tips

1. Deprecation and Compatibility

  • PHP Version: The package is unmaintained (last release in 2013). Test thoroughly with PHP 7.4+ or use a polyfill like ext-dom if errors arise.
  • Alternative: Consider modern alternatives like endroid/qr-code for active maintenance.

2. File Permissions

  • Ensure the output directory (e.g., storage/app/qr) is writable:
    mkdir -p storage/app/qr
    chmod -R 755 storage/app/qr
    

3. Memory Limits

  • Large QR codes (e.g., setSize(1000)) may hit PHP’s memory limit. Adjust memory_limit in php.ini or optimize image settings:
    $qrCode->setSize(500); // Balance between quality and memory
    

4. Debugging Rendering Issues

  • No Output? Verify the output path is correct and the directory exists. Use absolute paths for testing:
    $qrCode->render($data, __DIR__ . '/../../storage/app/qr/test.png');
    
  • Corrupted Images? Ensure no other processes are writing to the file simultaneously. Use unique filenames:
    $qrCode->render($data, "qr/{uniqid()}.png");
    

5. Error Correction Levels

  • Low Error Correction (L): Use for simple data (e.g., URLs). High error correction (H) may reduce capacity.
  • Testing: Validate QR codes using a scanner app or online validator.

6. Caching Strategies

  • Cache Generated QR Codes: Store hashes of input data to avoid regenerating identical codes:
    $cacheKey = md5($data);
    if (!Storage::exists("qr/{$cacheKey}.png")) {
        $qrCode->render($data, "qr/{$cacheKey}.png");
    }
    

7. Extending Functionality

  • Custom Colors: The library lacks built-in color customization. Use imagick or gd extensions post-generation:
    $image = imagecreatefrompng('qr.png');
    imagefilter($image, IMG_FILTER_GRAYSCALE);
    imagepng($image, 'qr_grayscale.png');
    

8. Security Considerations

  • Input Sanitization: Validate $data to prevent malicious payloads (e.g., XSS in URLs):
    $data = filter_var($request->input('data'), FILTER_SANITIZE_URL);
    
  • File Storage: Restrict QR code generation to trusted users or rate-limit endpoints to prevent abuse.

9. Testing

  • Unit Tests: Mock the QRCode class to test controller logic:
    $mock = Mockery::mock('Aferrandini\PHPQRCode\QRCode');
    $mock->shouldReceive('render')->once();
    
  • Integration Tests: Use Laravel’s Storage facade to verify file generation:
    $this->assertTrue(Storage::exists('qr/test.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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views