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

Laravel Pwa Laravel Package

erag/laravel-pwa

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require erag/laravel-pwa
    
  2. Publish configuration:

    php artisan erag:install-pwa
    

    This generates config/pwa.php and sets up the PWA structure.

  3. Add Blade directives to your main layout (resources/views/layouts/app.blade.php):

    <head>
        @PwaHead
        <!-- Other head tags -->
    </head>
    <body>
        <!-- Your content -->
        @RegisterServiceWorkerScript
    </body>
    
  4. Verify HTTPS (required for PWA functionality) and test on Chrome/Firefox.

First Use Case: Basic PWA Enablement

  • Configure config/pwa.php with your app’s name, icons, and theme colors.
  • Run php artisan erag:update-manifest to generate manifest.json and sw.js in public/pwa/.
  • Test by visiting your site on Chrome (DevTools > Application > Manifest) and checking the "Add to Home Screen" prompt.

Implementation Patterns

Core Workflow

  1. Configuration-Driven Setup:

    • Define PWA settings in config/pwa.php (e.g., name, icons, theme_color).
    • Use the facade to update dynamically:
      PWA::update(['name' => 'My App', 'theme_color' => '#3b82f6']);
      
    • Regenerate assets with php artisan erag:update-manifest.
  2. Frontend Integration:

    • Blade Directives:
      • @PwaHead: Injects <link rel="manifest">, theme color, and other meta tags.
      • @RegisterServiceWorkerScript: Adds the service worker registration script before </body>.
    • Livewire/Vue/React: Works out-of-the-box with the directives. For SPAs, ensure the service worker is registered after hydration.
  3. Dynamic Logo Updates:

    • Handle file uploads in a controller:
      public function updateLogo(Request $request) {
          $response = PWA::processLogo($request);
          return $response['status'] ? back()->with('success', $response['message']) : back()->withErrors($response['errors']);
      }
      
    • Validate uploads (PNG, 512x512px, <1024KB) via the facade’s built-in logic.
  4. Offline Support:

    • Customize resources/views/vendor/pwa/offline.blade.php for offline fallback pages.
    • Pre-cache critical assets by extending the service worker (see "Extension Points").

Integration Tips

  • Livewire: The @RegisterServiceWorkerScript directive works seamlessly. For Alpine.js, ensure the script runs after Livewire’s Alpine initialization.
  • Vue/React: Register the service worker in your app’s main.js/main.jsx after the app mounts to avoid conflicts:
    // main.js
    import { registerSW } from '/pwa/sw.js';
    import { createApp } from 'vue';
    
    const app = createApp(App);
    app.mount('#app');
    if ('serviceWorker' in navigator) {
        registerSW();
    }
    
  • Testing:
    • Use Chrome’s Lighthouse (npx lighthouse https://your-app.test) to audit PWA compliance.
    • Test offline mode by enabling "Offline" in Chrome DevTools (Application > Service Workers).
  • CI/CD: Add php artisan erag:update-manifest to your deploy script to ensure manifest.json is always up-to-date.

Gotchas and Tips

Pitfalls

  1. HTTPS Requirement:

    • PWAs only work on HTTPS. Use trustproxy middleware in app/Http/Kernel.php for local development:
      'trustProxies' => true,
      
    • Test locally with https://localhost via Laravel Valet or laravel serve --secure.
  2. Service Worker Caching:

    • The default service worker caches all routes. For dynamic apps, extend resources/js/pwa/sw.js to exclude certain routes:
      const urlsToCache = [
          '/',
          '/dashboard',
          // Exclude API routes
          '!/api/*'
      ];
      
    • Clear the cache during deployments by adding a version query string to assets:
      <link rel="stylesheet" href="{{ asset('css/app.css?v=' . filemtime(public_path('css/app.css')) }}">
      
  3. iOS Quirks:

    • iOS 13+ requires explicit user interaction (e.g., a button click) to trigger the install prompt. Enable the install button in config/pwa.php:
      'install-button' => true,
      
    • Test iOS-specific features using Safari’s "Add to Home Screen" simulation.
  4. File Permissions:

    • Ensure public/pwa/ is writable by the web server:
      chmod -R 755 public/pwa/
      
    • If using processLogo(), verify storage/app/public/pwa/ exists and is writable.
  5. Livewire Debugging:

    • If the service worker fails to register with Livewire, wrap the directive in a @once block:
      @once
          @RegisterServiceWorkerScript
      @endonce
      

Debugging Tips

  • Service Worker Errors:

    • Check the browser console for Failed to register a ServiceWorker errors. Common causes:
      • HTTPS missing.
      • Incorrect path to sw.js (should be /pwa/sw.js).
      • Ad blockers blocking the service worker.
    • Debug with:
      navigator.serviceWorker.register('/pwa/sw.js').catch(e => console.error('SW reg error:', e));
      
  • Manifest Validation:

    • Use Web.dev’s PWA Checker to validate manifest.json.
    • Common issues:
      • Missing short_name (required for iOS).
      • Incorrect icon sizes (must include 192x192px and 512x512px).
      • Invalid display mode (use standalone or fullscreen for best results).
  • Offline Debugging:

    • Enable "Offline" mode in Chrome DevTools (Application > Service Workers).
    • Test the offline page by navigating to /offline or simulating a network error.

Extension Points

  1. Custom Service Worker:

    • Override the default sw.js by publishing the template:
      php artisan vendor:publish --tag=pwa-assets
      
    • Edit resources/js/pwa/sw.js to add custom caching logic (e.g., Stale-While-Revalidate for APIs).
  2. Dynamic Manifest Updates:

    • Trigger updates via events (e.g., after a logo upload):
      event(new PWAUpdated($newManifestData));
      
    • Listen for updates in a service provider:
      PWAUpdated::dispatch($data);
      
  3. Push Notifications:

    • Extend the service worker to handle push events:
      // sw.js
      self.addEventListener('push', (event) => {
          const data = event.data.json();
          self.registration.showNotification(data.title, data.options);
      });
      
    • Use Laravel Echo/Pusher to send notifications from the backend.
  4. Background Sync:

    • Enable sync in the service worker:
      navigator.serviceWorker.ready.then((sw) => {
          sw.sync.register('sync-tasks');
      });
      
    • Handle sync events in sw.js:
      self.addEventListener('sync', (event) => {
          if (event.tag === 'sync-tasks') {
              // Retry failed requests
          }
      });
      

Configuration Quirks

  • debug Mode:

    • Set 'debug' => true in config/pwa.php to log service worker events to the console. Disable in production.
  • Livewire App Mode:

    • Enable 'livewire-app' => true if using Livewire’s SPA mode. This adjusts the service worker registration strategy.
  • Icon Paths:

    • Icons must be placed in public/pwa/icons/ and referenced in config/pwa.php:
      'icons' => [
          ['src' => 'icons/icon-192x192.png', 'sizes' => '192x192'],
          ['src' => 'icons/icon-512x512.png', 'sizes' => '512x512'],
      ],
      
    • Use relative paths (e.g., icons/logo.png) for assets in the same directory.

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
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