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

Filament Barcode Scanner Field Laravel Package

marcelorodrigo/filament-barcode-scanner-field

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require marcelorodrigo/filament-barcode-scanner-field
    

    Publish assets (optional for customization):

    php artisan vendor:publish --tag=filament-barcode-scanner-field-assets
    
  2. First Use Case: Add the scanner field to a Filament form:

    use Marcelorodrigo\FilamentBarcodeScannerField\Forms\Components\BarcodeInput;
    
    BarcodeInput::make('product_barcode')
        ->required()
        ->label('Scan Product Barcode')
        ->columnSpanFull(),
    
  3. Where to Look First:

    • Documentation: Check the GitHub README for basic usage examples.
    • Source: Review src/Forms/Components/BarcodeInput.php for method signatures and configuration options.
    • Blade Views: Inspect resources/views/components/barcode-input.blade.php for UI structure.

Implementation Patterns

Core Workflow

  1. Form Integration: Replace traditional TextInput with BarcodeInput for barcode/QR scanning:

    BarcodeInput::make('scanned_code')
        ->live(onBlur: true) // Auto-submit on blur
        ->rules(['required', 'string'])
        ->columnSpan('full'),
    
  2. Modal Handling: The scanner opens in a modal triggered by clicking the input field. Configure modal behavior:

    BarcodeInput::make('qr_code')
        ->modalWidth('lg') // Adjust modal size
        ->modalMaximizeButton() // Add maximize button
        ->modalCloseButton(), // Add close button
    
  3. Real-Time Feedback: Use events to handle scan results:

    BarcodeInput::make('tracking_number')
        ->extraAttributes([
            'x-on:scanned' => 'handleScan($event.detail)',
        ]),
    

    Then add JavaScript in your form's Blade view:

    <script>
        function handleScan(scannedData) {
            console.log('Scanned:', scannedData);
            // Trigger form submission or update state
        }
    </script>
    
  4. Validation & Processing: Chain validation rules or use Filament's built-in validation:

    BarcodeInput::make('serial_number')
        ->rules([
            'required',
            'string',
            function ($attribute, $value, $fail) {
                if (!preg_match('/^[A-Z0-9]{12}$/', $value)) {
                    $fail('Invalid barcode format.');
                }
            },
        ]),
    
  5. Asset Customization: Override default styles by publishing assets and extending the CSS:

    /* resources/css/filament/barcode-scanner-field.css */
    .fi-barcode-scanner-modal {
        --fi-barcode-scanner-bg: #1a1a2e;
    }
    

Integration Tips

  • Livewire/Alpine Sync: Use wire:model or Alpine.js to sync scanned values with Livewire components:

    BarcodeInput::make('livewire_sync')
        ->wireModel('scannedValue'),
    
    <x-barcode-input wire:model="scannedValue" />
    
  • Multi-Field Forms: Combine with other Filament components for complex workflows:

    $form->schema([
        BarcodeInput::make('primary_barcode'),
        TextInput::make('manual_fallback')
            ->hidden(fn ($state) => $state['primary_barcode'] !== null),
    ]);
    
  • Conditional Logic: Show/hide the scanner based on conditions:

    BarcodeInput::make('conditional_scan')
        ->visible(fn ($record) => $record->requires_scanning),
    

Gotchas and Tips

Common Pitfalls

  1. Camera Permissions:

    • Issue: Scanner fails silently if camera permissions are denied.
    • Fix: Test on mobile/desktop with camera access. Add user guidance:
      BarcodeInput::make('scan_here')
          ->helperText('Ensure camera permissions are enabled in browser settings.'),
      
  2. Mobile vs. Desktop:

    • Issue: QR codes may not scan reliably on all devices.
    • Fix: Test on target devices. Use modalWidth('full') for better mobile UX:
      BarcodeInput::make('mobile_scan')
          ->modalWidth('full')
          ->modalMaximizeButton(),
      
  3. Asset Loading:

    • Issue: Custom CSS/JS not loading.
    • Fix: Ensure assets are published and Filament's Asset Manager is configured:
      // In ServiceProvider
      FilamentAsset::register([...], 'marcelorodrigo/filament-barcode-scanner-field');
      
  4. Conflict with Other Packages:

    • Issue: JavaScript conflicts with other Filament plugins.
    • Fix: Isolate scanner scripts by using unique IDs:
      BarcodeInput::make('unique_scan')
          ->extraAttributes(['data-scanner-id' => 'custom-scanner-123']),
      

Debugging Tips

  1. Console Logs: Enable debug mode in the scanner's JavaScript:

    BarcodeInput::make('debug_scan')
        ->extraAttributes(['data-debug' => 'true']),
    

    Check browser console for scan events:

    EventListener fired: scanned -> { detail: '123456789012' }
    
  2. Network Requests:

    • Use browser dev tools to inspect XHR requests if the scanner triggers unexpected API calls.
    • Verify Filament's CSRF token is included in requests.
  3. View Overrides:

    • If the scanner modal doesn’t render, check:
      • Published views exist in resources/views/vendor/filament-barcode-scanner-field/.
      • No syntax errors in Blade templates.

Extension Points

  1. Custom Scanning Logic: Override the scanner’s JavaScript by extending the package:

    // resources/js/filament/barcode-scanner.js
    document.addEventListener('alpine:init', () => {
        Alpine.data('customScanner', () => ({
            init() {
                // Extend default scanner behavior
            },
        }));
    });
    

    Then attach to the component:

    BarcodeInput::make('custom_scan')
        ->extraAttributes(['x-data' => 'customScanner()']),
    
  2. New Barcode Formats: Extend the scanner’s supported formats by modifying the JavaScript library (e.g., ZXing):

    BarcodeInput::make('extended_scan')
        ->extraAttributes([
            'data-formats' => 'CODE_128,PDF_417,EAN_8',
        ]),
    
  3. Server-Side Processing: Handle scanned data in Livewire hooks:

    public function handleScan(string $scannedData): void
    {
        $this->validateScannedData($scannedData);
        $this->processBarcode($scannedData);
    }
    

Configuration Quirks

  1. Modal Z-Index:

    • If the scanner modal appears behind other modals, increase its z-index in CSS:
      .fi-barcode-scanner-modal {
          z-index: 9999 !important;
      }
      
  2. Auto-Focus:

    • The scanner may not auto-focus on mobile. Force focus via JavaScript:
      BarcodeInput::make('auto_focus_scan')
          ->extraAttributes(['autofocus' => 'autofocus']),
      
  3. Fallback for Unsupported Browsers:

    • Provide a fallback input for browsers without camera support:
      BarcodeInput::make('fallback_scan')
          ->fallback(
              TextInput::make('manual_entry')
                  ->placeholder('Enter barcode manually')
          ),
      

Performance Tips

  1. Lazy Loading: Load the scanner’s JavaScript only when needed:

    BarcodeInput::make('lazy_scan')
        ->extraAttributes(['x-load' => 'lazy']),
    
  2. Debounce Scanning: Reduce rapid scans by debouncing the scanned event:

    // In your form's Alpine.js
    <script>
        let scanDebounce;
        document.addEventListener('scanned', (e) => {
            clearTimeout(scanDebounce);
            scanDebounce = setTimeout(() => {
                // Process scan
            }, 300);
        });
    </script>
    
  3. Asset Optimization: Minify custom CSS/JS before publishing:

    npm run dev -- --watch
    
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