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

ascsoftw/livewire-toast

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ascsoftw/livewire-toast
    
  2. Add to Layout: Place @livewire('livewire-toast') in your main layout file (e.g., resources/views/layouts/app.blade.php), ideally near the closing </body> tag for proper positioning.

  3. First Toast: Emit a test toast from a Livewire component:

    $this->emitTo('livewire-toast', 'show', 'Hello, Toast!');
    

Key Files to Review

  • Component: vendor/ascsoftw/livewire-toast/src/LivewireToast.php (core logic)
  • Blade View: vendor/ascsoftw/livewire-toast/resources/views/livewire/livewire-toast.blade.php (customization entry point)
  • Tailwind Styling: Inspect the default classes in the Blade file for quick theming.

Implementation Patterns

Core Workflows

  1. Livewire Component Emission: Use $this->emitTo() in Livewire methods to trigger toasts dynamically:

    public function saveProject()
    {
        if ($this->validate()) {
            $this->emitTo('livewire-toast', 'showSuccess', 'Project saved!');
            // ...
        } else {
            $this->emitTo('livewire-toast', 'showError', 'Validation failed.');
        }
    }
    
  2. Session Flash Integration: Leverage Laravel’s session for toasts that persist across requests (e.g., after form submissions):

    public function store(Request $request)
    {
        $validated = $request->validate([...]);
        Project::create($validated);
        return redirect()->back()->with('livewire-toast', [
            'type' => 'success',
            'message' => 'Project created!'
        ]);
    }
    
  3. Conditional Toasts: Combine with Livewire’s reactivity for dynamic messages:

    public $isSuccess = false;
    public function attemptAction()
    {
        $this->isSuccess = true; // Simulate success
        $this->emitTo('livewire-toast', 'show', [
            'type' => $this->isSuccess ? 'success' : 'error',
            'message' => $this->isSuccess ? 'Action succeeded!' : 'Action failed.'
        ]);
    }
    
  4. View-Based Emission: For non-Livewire Blade views, use the $emitTo helper (if registered globally):

    @if(session('livewire-toast'))
        @php
            $emitTo('livewire-toast', 'show', session('livewire-toast'));
        @endphp
    @endif
    

Integration Tips

  • Auto-Dismissal: Defaults to 5 seconds. Override via config (see Gotchas) or per-toast:
    $this->emitTo('livewire-toast', 'show', [
        'message' => 'Custom duration',
        'duration' => 10000 // 10 seconds
    ]);
    
  • Queueing Toasts: Emit multiple toasts in quick succession; the package handles stacking.
  • Theming: Extend Tailwind classes in the Blade file (e.g., bg-blue-500 for custom colors).
  • Accessibility: Ensure toast messages are ARIA-compliant (e.g., role="alert" in the Blade template).

Gotchas and Tips

Pitfalls

  1. Missing Component:

    • Error: Class 'LivewireToast' not found.
    • Fix: Ensure @livewire('livewire-toast') is placed in a layout file loaded on every request (e.g., app.blade.php).
  2. Session Flash Not Triggering:

    • Error: Toasts from session()->flash() don’t appear.
    • Fix: Verify the session key is exactly 'livewire-toast' (case-sensitive). Check if middleware (e.g., ShareErrorsFromSession) is interfering.
  3. Duplicate Toasts:

    • Cause: Emiting the same toast multiple times rapidly.
    • Fix: Use a unique ID or debounce emissions:
      $this->emitTo('livewire-toast', 'show', ['id' => uniqid(), 'message' => '...']);
      
  4. Styling Overrides:

    • Issue: Tailwind classes are ignored.
    • Debug: Ensure no CSS specificity conflicts (e.g., !important in global styles). Inspect the rendered HTML for applied classes.
  5. AlpineJS Conflicts:

    • Symptom: Toasts flicker or fail to dismiss.
    • Fix: Avoid reinitializing AlpineJS on the same element. If using Alpine elsewhere, isolate the toast component’s DOM.

Debugging

  • Check Emissions: Use Livewire’s wire:click or wire:model events to verify emissions:
    <button wire:click="testToast">Test Toast</button>
    
    public function testToast()
    {
        $this->emitTo('livewire-toast', 'show', 'Debug message');
    }
    
  • Inspect Network Tab: Look for Livewire events (e.g., livewire-toast@show) in the browser’s DevTools.
  • Log Toast Data: Add debug logs in the component’s show() method (override the package’s component if needed).

Configuration Quirks

  • No Config File: The package uses hardcoded defaults (e.g., duration: 5000). To customize:
    1. Publish the config (if available; check for livewire-toast:publish).
    2. Override via Blade (e.g., pass duration in the emit array).
  • Type Validation: Supported types are success, error, warning, info. Passing unsupported types (e.g., 'custom') may render as default styling.

Extension Points

  1. Custom Toast Types: Extend the Blade template to support additional types (e.g., danger):
    @if($type === 'danger')
        <div class="bg-red-500 text-white">...</div>
    @endif
    
  2. Progressive Enhancement: Use AlpineJS to add interactivity (e.g., pause on hover):
    <div x-data="{ paused: false }" @mouseenter="paused = true" @mouseleave="paused = false">
        <!-- Toast content -->
    </div>
    
    // In LivewireToast.php
    $this->dispatchBrowserEvent('pause-toast', ['paused' => true]);
    
  3. Queue System: Implement a queue for toasts (e.g., using Laravel Queues) to handle high-frequency emissions:
    Queue::push(function () {
        $this->emitTo('livewire-toast', 'show', 'Queued toast');
    });
    
  4. Localization: Wrap messages in __() for translation support:
    $this->emitTo('livewire-toast', 'show', __('toast.project_saved'));
    
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