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 Toaster Laravel Package

masmerise/livewire-toaster

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require masmerise/livewire-toaster
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Masmerise\LivewireToaster\LivewireToasterServiceProvider"
    
  2. Include the Toaster in your layout: Add this to your main layout file (e.g., resources/views/layouts/app.blade.php):

    @livewireScripts
    @toasterScripts
    
  3. First Toast: Dispatch a toast from a Livewire component:

    use Masmerise\LivewireToaster\Facades\Toaster;
    
    public function save()
    {
        Toaster::success('Item saved successfully!');
        // ... rest of your logic
    }
    

    Or from a controller:

    Toaster::warning('This action cannot be undone.');
    

Where to Look First

  • Config File: config/livewire-toaster.php (for customization like position, duration, or appearance).
  • Blade Directive: @toasterScripts (ensures the toast UI is rendered).
  • Facade Methods: Toaster::success(), Toaster::error(), etc. (documented in the README).

Implementation Patterns

Core Workflows

  1. Livewire Component Integration: Dispatch toasts directly in component methods (e.g., after form submission):

    public function updateProfile()
    {
        if ($this->validate()) {
            Toaster::success('Profile updated!');
            // ...
        } else {
            Toaster::error('Validation failed.');
        }
    }
    
  2. Controller Integration: Useful for non-Livewire actions (e.g., API responses or redirects):

    public function destroy($id)
    {
        $model = Model::findOrFail($id);
        $model->delete();
        Toaster::info('Item deleted.');
        return redirect()->back();
    }
    
  3. Conditional Toasts: Combine with logic to show context-aware messages:

    public function process()
    {
        if ($this->isAdmin()) {
            Toaster::success('Admin action completed.');
        } else {
            Toaster::warning('You lack permissions for this action.');
        }
    }
    

Advanced Patterns

  1. Custom Toast Content: Pass HTML or arrays for rich toasts:

    Toaster::success('New <strong>user</strong> added.', [
        'title' => 'User Created',
        'timeout' => 5000,
    ]);
    
  2. Queueing Toasts: Use Toaster::queue() to batch notifications (e.g., after bulk operations):

    foreach ($items as $item) {
        Toaster::queue()->info("Processed {$item->name}");
    }
    Toaster::flush(); // Display all queued toasts
    
  3. Livewire Event Integration: Trigger toasts from JavaScript events (e.g., after AJAX calls):

    Livewire.emit('toast', { type: 'success', message: 'Data loaded!' });
    

    Handle in Livewire:

    protected $listeners = ['toast' => 'handleToast'];
    
    public function handleToast($event)
    {
        Toaster::{$event['type']}($event['message']);
    }
    
  4. Theming: Override default styles via the config or custom CSS:

    /* resources/css/app.css */
    .toaster-success { background: #4CAF50; }
    

Gotchas and Tips

Common Pitfalls

  1. Missing @toasterScripts:

    • Symptom: Toasts don’t appear.
    • Fix: Ensure @toasterScripts is included in your layout after @livewireScripts.
  2. Toast Not Showing in Redirects:

    • Cause: Toasts rely on Livewire’s reactivity. Redirecting bypasses the Livewire context.
    • Workaround: Use Toaster::flash() for redirects (requires session storage):
      Toaster::flash('success', 'Redirecting...', 'You will be redirected shortly.');
      return redirect()->route('target');
      
  3. JavaScript Conflicts:

    • Cause: Duplicate Livewire or Alpine.js instances.
    • Fix: Ensure no other packages are loading conflicting scripts. Check for multiple @livewireScripts calls.
  4. Queue Not Flushing:

    • Cause: Forgetting Toaster::flush() after queuing multiple toasts.
    • Tip: Use a finally block or wrap in a try-catch to ensure flushing.

Debugging Tips

  1. Check the Console: Open browser dev tools (F12) to verify:

    • No JavaScript errors (e.g., Livewire is not defined).
    • The Toaster script is loaded (@toasterScripts).
  2. Inspect Network Requests: Ensure no 404s for /vendor/masmerise/livewire-toaster/dist/toaster.js.

  3. Clear Config Cache: If changes to config/livewire-toaster.php aren’t reflected:

    php artisan config:clear
    

Extension Points

  1. Custom Toast Types: Extend the facade to add your own methods:

    // app/Providers/AppServiceProvider.php
    use Masmerise\LivewireToaster\Facades\Toaster;
    
    Toaster::extend('custom', function ($message, $options = []) {
        return Toaster::make('custom', $message, $options + ['icon' => '🎉']);
    });
    

    Usage:

    Toaster::custom('Special event!');
    
  2. Override Default Views: Publish and modify the toast blade template:

    php artisan vendor:publish --tag=livewire-toaster-views
    

    Edit resources/views/vendor/livewire-toaster/toast.blade.php.

  3. Dynamic Positioning: Use the position option in the config or per-toast:

    Toaster::success('Message', ['position' => 'top-right']);
    
  4. Localization: Customize messages via language files (resources/lang/en/toaster.php):

    return [
        'success' => 'Operation completed!',
    ];
    

    Override in your toast call:

    Toaster::success(__('toaster.success'));
    

Pro Tips

  • Batch Operations: Use Toaster::queue() for bulk actions (e.g., import/export) to avoid overwhelming users.
  • Accessibility: Add aria-live="polite" to the toast container for screen readers:
    <div id="toaster" aria-live="polite">
        @livewire('toaster')
    </div>
    
  • Performance: For high-frequency toasts (e.g., real-time updates), consider debouncing or grouping messages.
  • Testing: Use Toaster::shouldReceive() in PHPUnit to assert toasts are dispatched:
    Toaster::shouldReceive('success')->once()->with('Test message');
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle