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

Laravelpwa Laravel Package

silviolleite/laravelpwa

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require silviolleite/laravelpwa
    

    Publish the package assets:

    php artisan vendor:publish --provider="SilvioLeite\LaravelPWA\LaravelPWAServiceProvider" --tag="pwa"
    

    Add the middleware to app/Http/Kernel.php:

    'web' => [
        // ...
        \SilvioLeite\LaravelPWA\Middleware\PWA::class,
    ],
    
  2. First Use Case:

    • Visit your site on a mobile device (HTTPS required). The browser will prompt users to "Add to Home Screen".
    • Ensure your app has a manifest file (/public/manifest.json) and a service worker (/public/sw.js) generated by the package.
  3. Key Files to Inspect:

    • /resources/views/vendor/pwa/ (PWA-specific Blade templates)
    • /config/pwa.php (Configuration for icons, colors, and service worker)
    • /public/manifest.json (Auto-generated PWA manifest)

Implementation Patterns

Core Workflows

  1. Manifest Customization:

    • Modify /config/pwa.php to define:
      'name' => 'My App',
      'short_name' => 'App',
      'start_url' => '/',
      'display' => 'standalone', // 'fullscreen', 'minimal-ui', etc.
      'background_color' => '#ffffff',
      'theme_color' => '#4285f4',
      'icons' => [
          ['src' => '/icons/icon-72x72.png', 'sizes' => '72x72', 'type' => 'image/png'],
          ['src' => '/icons/icon-192x192.png', 'sizes' => '192x192', 'type' => 'image/png'],
          // Add more icon sizes as needed
      ],
      
    • Place icons in /public/icons/ (e.g., icon-192x192.png).
  2. Service Worker Integration:

    • The package generates a basic sw.js in /public/sw.js. Extend it by:
      • Overriding the default service worker template in /resources/views/vendor/pwa/sw.blade.php.
      • Using the pwa:generate Artisan command to regenerate assets after changes:
        php artisan pwa:generate
        
  3. SPA-Like Navigation:

    • Since PWAs rely on client-side routing, ensure your app uses history API (e.g., Laravel Mix + Vue/React Router) or server-side routing with full-page reloads (if using traditional Laravel Blade).
    • Example for Blade:
      <a href="{{ route('dashboard') }}" data-pwa-ignore>Dashboard</a>
      
      Use data-pwa-ignore for links that should not trigger the service worker cache.
  4. Offline Support:

    • Cache critical assets by extending the service worker:
      // In /resources/views/vendor/pwa/sw.blade.php
      self.addEventListener('install', (event) => {
          event.waitUntil(
              caches.open('my-app-cache').then((cache) => {
                  return cache.addAll([
                      '/',
                      '/css/app.css',
                      '/js/app.js',
                      // Add other critical assets
                  ]);
              })
          );
      });
      
  5. Dynamic Manifest Updates:

    • Use the PWA facade to generate the manifest dynamically:
      use SilvioLeite\LaravelPWA\Facades\PWA;
      $manifest = PWA::manifest();
      

Integration Tips

  1. With Laravel Mix:

    • Ensure your webpack.mix.js copies the generated manifest.json and sw.js:
      mix.copy('public/manifest.json', 'public/manifest.json')
         .copy('public/sw.js', 'public/sw.js');
      
  2. With Inertia.js:

    • PWAs work seamlessly with Inertia due to its client-side routing. Ensure your sw.js caches the root page and Inertia’s entry point:
      cache.addAll([
          '/',
          '/js/app.js', // Inertia entry point
      ]);
      
  3. Testing:

    • Use Chrome DevTools (Application > Manifest and Service Workers) to debug.
    • Test offline mode by enabling "Offline" in DevTools’ Application tab.
  4. Fallback for Non-PWA Browsers:

    • Serve a fallback HTML file if the browser doesn’t support PWAs:
      // In app/Http/Middleware/PWA.php
      if (!PWA::isSupported()) {
          return response()->view('fallback');
      }
      

Gotchas and Tips

Pitfalls

  1. HTTPS Requirement:

    • PWAs only work on HTTPS (or localhost). Use tools like Laravel Valet or ngrok for local testing.
    • Workaround: Disable PWA checks in development by setting:
      'debug' => env('APP_ENV') === 'local',
      
      in /config/pwa.php.
  2. Service Worker Caching Issues:

    • If changes to sw.js aren’t reflected, clear the service worker cache in Chrome DevTools (Application > Service Workers > Unregister).
    • Use a unique cache version name to force updates:
      const CACHE_VERSION = 'v2'; // Increment this to bust cache
      
  3. Manifest Not Updating:

    • After modifying /config/pwa.php, regenerate assets:
      php artisan pwa:generate
      
    • Ensure the manifest.json path in your Blade layout is correct:
      <link rel="manifest" href="{{ asset('manifest.json') }}">
      
  4. Android Prompt Delays:

    • Android may delay the "Add to Home Screen" prompt. Ensure:
      • The site is fully interactive before the user leaves the page.
      • The start_url in manifest.json points to a valid, interactive page.
  5. iOS Limitations:

    • iOS has stricter PWA requirements (e.g., no splash screen customization). Test on real devices, as Safari’s PWA support is less mature than Chrome’s.

Debugging Tips

  1. Check Console Errors:

    • Open Chrome DevTools (Console) to catch issues like:
      • Failed to register a ServiceWorker (HTTPS or path issues).
      • Manifest: Line: X, column: Y, Syntax error (invalid JSON in manifest.json).
  2. Validate Manifest:

  3. Service Worker Debugging:

    • Listen for events in sw.js:
      self.addEventListener('fetch', (event) => {
          console.log('Fetch event:', event.request.url);
      });
      
  4. Lighthouse Audit:

    • Run a PWA audit in Chrome DevTools (Lighthouse) to identify missing features (e.g., splash screen, offline support).

Extension Points

  1. Custom Service Worker Logic:

    • Override the default sw.js by publishing the template:
      php artisan vendor:publish --provider="SilvioLeite\LaravelPWA\LaravelPWAServiceProvider" --tag="pwa-views"
      
    • Edit /resources/views/vendor/pwa/sw.blade.php and add custom logic (e.g., precaching routes).
  2. Dynamic Manifest Data:

    • Extend the PWA facade to inject dynamic data (e.g., user-specific icons):
      PWA::extend(function ($manifest) {
          $manifest['icons'][] = [
              'src' => '/user-avatars/' . auth()->id() . '.png',
              'sizes' => '192x192',
          ];
      });
      
  3. Conditional PWA Enablement:

    • Disable PWA for specific routes or user roles:
      if (Auth::check() && Auth::user()->is_admin) {
          return response()->view('admin.dashboard');
      }
      // PWA middleware will run otherwise
      
  4. Custom Icons for Different Devices:

    • Use Laravel’s request() helper to serve device-specific icons:
      'icons' => collect([
          ['src' => '/icons/icon-192x192.png', 'sizes' => '192x192'],
      ])->when(request()->userAgent()->is('iPhone'), function ($icons) {
          $icons->push(['src' => '/icons/apple-touch-icon.png', 'sizes' => '180x180']);
      })->toArray(),
      

Performance Quirks

  1. Service Worker Registration Timing:
    • Register the service worker after the DOM is loaded to avoid blocking
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.
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
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours