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

Livewire Toast Laravel Package

theabhishekin/livewire-toast

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require theabhishekin/livewire-toast
    
  2. Add Toast Container: Place @livewire('toast-container') in your main layout (e.g., resources/views/layouts/app.blade.php), typically near the <body> opening tag for optimal visibility.

  3. Import JavaScript: Add the toast script to your entry file (e.g., resources/js/app.js):

    import '../../vendor/theabhishekin/livewire-toast/resources/js/toast';
    
  4. First Toast: Dispatch a toast from a Livewire component:

    $this->dispatch('toast', [
        'title' => 'Success!',
        'type' => 'success',
    ]);
    

First Use Case

Trigger a success toast after a form submission:

public function save()
{
    $this->validate([...]);

    // Save logic...

    $this->dispatch('toast', [
        'title' => 'Saved successfully!',
        'type' => 'success',
        'description' => 'Your changes have been saved.',
    ]);

    return redirect()->to('/');
}

Implementation Patterns

Core Workflows

  1. Component Integration:

    • Use $this->dispatch('toast', [...]) in Livewire methods (e.g., mount(), updatedProperty(), or event handlers).
    • Example for conditional toasts:
      if ($this->isValid()) {
          $this->dispatch('toast', ['title' => 'Valid!', 'type' => 'success']);
      }
      
  2. Dynamic Toasts:

    • Pass variables from Livewire to Alpine via dispatch:
      $this->dispatch('toast', [
          'title' => 'User ' . $user->name . ' created',
          'type' => 'info',
      ]);
      
  3. Action Buttons:

    • Add interactive buttons to toasts:
      $this->dispatch('toast', [
          'title' => 'Action required',
          'type' => 'warning',
          'actions' => [
              ['text' => 'Retry', 'url' => route('retry')],
              ['text' => 'Dismiss', 'event' => 'toast.dismiss'],
          ],
      ]);
      
  4. Positioning:

    • Override default position (e.g., bottom-right) via config or per-toast:
      $this->dispatch('toast', [
          'title' => 'Alert',
          'position' => 'bottom-right',
      ]);
      
  5. Auto-Dismiss:

    • Control duration (ms) globally in config/livewire-toast.php or per-toast:
      $this->dispatch('toast', [
          'title' => 'Temporary',
          'duration' => 3000, // 3 seconds
      ]);
      

Integration Tips

  • Dark Mode: Ensure your theme supports data-[dark] attributes (handled automatically via Alpine).
  • Stacking: Limit visible toasts via maxVisible in config (default: 5).
  • Livewire Events: Listen for toast events in Alpine:
    document.addEventListener('toast.show', (e) => {
        console.log('Toast shown:', e.detail);
    });
    
  • Custom Styling: Extend the toast container’s classes (e.g., .livewire-toast-container) in your CSS.

Gotchas and Tips

Pitfalls

  1. JavaScript Loading Order:

    • Ensure toast.js is imported after Alpine.js (if not using Vite/Laravel Mix auto-ordering).
    • Fix: Move the import to the end of app.js or use defer.
  2. Duplicate Toasts:

    • Rapid dispatches may stack unexpectedly. Use duration: 0 for persistent toasts or debounce dispatches:
      if (!$this->hasToastShown) {
          $this->dispatch('toast', [...]);
          $this->hasToastShown = true;
      }
      
  3. Alpine Conflicts:

    • If using other Alpine-based packages, namespace Alpine components in the toast script:
      // In toast.js, replace `Alpine.store` with:
      window.Alpine.store('toast', { ... });
      
  4. Livewire Re-renders:

    • Toasts may flicker if the container re-renders. Anchor the container to a stable DOM node (e.g., #app).
  5. Config Publishing:

    • Forgetting to publish config (php artisan vendor:publish --tag=livewire-toast-config) means using defaults only.

Debugging

  • Toast Not Showing?:

    • Check browser console for Alpine/JS errors.
    • Verify the container is rendered (@livewire('toast-container') exists in the DOM).
    • Ensure no JS errors block the toast script.
  • Styling Issues:

    • Override default classes (e.g., .livewire-toast) in your CSS:
      .livewire-toast { --tw-bg-opacity: 0.95; } /* Example: Adjust backdrop */
      
  • Event Listeners:

    • Debug Alpine events with:
      window.Alpine.on('toast.show', (e) => console.log(e.detail));
      

Extension Points

  1. Custom Toast Types:

    • Extend the types array in config to add themes (e.g., ['custom']).
    • Override colors in CSS:
      .livewire-toast-custom { --tw-bg-color: #3b82f6; }
      
  2. Global Toast State:

    • Access toasts via Alpine store:
      const toasts = Alpine.store('toast').toasts;
      
  3. Server-Side Logic:

    • Use Livewire hooks to trigger toasts:
      protected $listeners = ['toast.trigger' => 'showToast'];
      
      public function showToast($data) {
          $this->dispatch('toast', $data);
      }
      
  4. Testing:

    • Mock toasts in PHPUnit:
      $this->dispatchBrowserEvent('toast', ['title' => 'Test']);
      $this->assertLivewireDispatches('toast');
      
  5. Performance:

    • For high-frequency toasts (e.g., real-time updates), batch dispatches:
      $this->dispatch('toast.batch', [
          ['title' => 'Update 1'],
          ['title' => 'Update 2', 'type' => 'info'],
      ]);
      
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope