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

devrabiul/laravel-toaster-magic

Dependency-free toast notifications for Laravel with Livewire v3/v4 support. Drop-in, customizable toasts with multiple modern themes, RTL + dark mode, XSS-safe links, and no need for jQuery, Bootstrap, or Tailwind.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require devrabiul/laravel-toaster-magic
    php artisan vendor:publish --provider="Devrabiul\ToastMagic\ToastMagicServiceProvider"
    

    (Assets auto-publish on first page load.)

  2. Add to Blade:

    <head>
        {!! ToastMagic::styles() !!}
    </head>
    <body>
        {!! ToastMagic::scripts() !!}
    </body>
    
  3. First Toast:

    use Devrabiul\ToastMagic\Facades\ToastMagic;
    
    ToastMagic::success('Success!', 'Your data has been saved.');
    

First Use Case

Trigger a success toast in a controller after a form submission:

public function store(Request $request) {
    $request->validate([...]);
    // Save data...
    ToastMagic::success('Record Saved', 'Your changes have been successfully saved.');
    return back();
}

Implementation Patterns

Controller Workflows

Standard Toast Usage:

// Basic
ToastMagic::success('Title', 'Description');

// With options
ToastMagic::error('Error!', 'Something went wrong.', [
    'showCloseBtn' => true,
    'customBtnLink' => route('dashboard'),
]);

// Validation errors
ToastMagic::error($validator->errors());

Fluent Dispatch Pattern (for complex setups):

ToastMagic::dispatch()
    ->success('User Created', 'Profile saved successfully.')
    ->withOptions([
        'timeOut' => 8000,
        'theme' => 'material'
    ]);

Livewire Integration

  1. Enable in config:

    'livewire_enabled' => true,
    'livewire_version' => 'v4', // or 'v3'
    
  2. Dispatch from component:

    $this->dispatch('toastMagic', [
        'status' => 'success',
        'title' => 'Updated!',
        'message' => 'Your profile has been updated.',
        'options' => ['customBtnText' => 'View Profile']
    ]);
    
  3. Handle in JavaScript:

    document.addEventListener('toastMagic', event => {
        const { status, title, message, options } = event.detail;
        toastMagic[status](title, message, options);
    });
    

JavaScript Patterns

AJAX Responses:

axios.post('/api/endpoint')
    .then(() => toastMagic.success('Success', 'Operation completed'))
    .catch(() => toastMagic.error('Error', 'Failed to process request'));

Dynamic Theming:

// Switch theme based on user preference
const userTheme = localStorage.getItem('theme');
toastMagic.setTheme(userTheme || 'default');

Common Integration Points

  1. Global Configuration:

    // config/laravel-toaster-magic.php
    'options' => [
        'positionClass' => 'toast-bottom-end',
        'theme' => 'glassmorphism',
        'pauseOnHover' => true,
    ]
    
  2. Theme Switching Middleware:

    public function handle($request, Closure $next) {
        if ($request->user()->prefers_dark_mode) {
            ToastMagic::setTheme('neon');
        }
        return $next($request);
    }
    
  3. Custom Toast Component (for Blade):

    @component('toast-magic::toast', [
        'type' => 'info',
        'title' => 'Notification',
        'message' => 'This is a custom toast component'
    ])
    @endcomponent
    

Gotchas and Tips

Common Pitfalls

  1. XSS Vulnerabilities:

    • Never pass unescaped user input directly:
      // UNSAFE
      ToastMagic::success('Hello, ' . $userInput);
      
      // SAFE
      ToastMagic::success('Hello, ' . e($userInput));
      
  2. Duplicate Toasts:

    • Enable preventDuplicates in config to avoid stacking identical toasts.
  3. Livewire Version Mismatch:

    • Ensure livewire_version in config matches your installed Livewire version (v3/v4).
  4. Session Flashing:

    • Toasts flashed via session()->flash() won't appear unless explicitly handled in your layout.

Debugging Tips

  1. Check Asset Loading:

    • Verify ToastMagic::styles() and ToastMagic::scripts() are in the correct Blade positions.
  2. Console Errors:

    • Look for toastMagic is not defined → Ensure scripts are loaded before DOM ready.
  3. Theme Conflicts:

    • If themes don't apply, check for CSS specificity issues with your global styles.
  4. Livewire Debugging:

    • Add this to your Livewire component to verify dispatch:
      dd($this->dispatch('toastMagic', [...]));
      

Configuration Quirks

  1. Per-Toast Overrides:

    • timeOut and showDuration in options override global config for that toast only.
  2. Position Classes:

    • Custom position classes must include toast-{position} (e.g., toast-custom-position).
  3. Dark Mode:

    • Requires theme="dark" on <body> tag, not a config setting.
  4. Gradient Mode:

    • Only works with default, material, or neumorphism themes.

Extension Points

  1. Custom Themes:

    • Add new themes by extending the SCSS in resources/css/toast-magic.scss.
  2. JavaScript Hooks:

    // Override default behavior
    toastMagic.on('show', (toast) => {
        console.log('Toast shown:', toast);
    });
    
  3. Livewire Event Filtering:

    document.addEventListener('toastMagic', (e) => {
        if (e.detail.status === 'warning') {
            e.preventDefault();
            // Custom handling for warnings
        }
    });
    
  4. Vite Integration:

    // config/laravel-toaster-magic.php
    'use_vite' => env('APP_ENV') === 'local',
    

Performance Tips

  1. Disable Auto-Dismiss:

    ToastMagic::success('Important', 'This toast stays until dismissed.', [
        'timeOut' => 0
    ]);
    
  2. Batch Processing:

    • For bulk operations, queue toasts to avoid UI lag:
      const queue = [];
      // ... process items ...
      queue.forEach(item => {
          toastMagic.success(`Processed ${item}`);
      });
      
  3. Lazy Loading:

    • Load scripts dynamically if not needed on all pages:
      @if(auth()->check())
          {!! ToastMagic::scripts() !!}
      @endif
      

Security Reminders

  1. Button Links:

    • Only http://, https://, /, and # URLs are sanitized by default.
  2. Message Content:

    • Future v3.0.0 will escape HTML by default (opt-in for raw HTML).
  3. CSRF Protection:

    • Ensure all custom button links include CSRF tokens if they trigger state-changing actions.

Advanced Patterns

  1. Toast Stack Management:

    // Clear all toasts
    toastMagic.clear();
    
    // Get current stack
    console.log(toastMagic.getStack());
    
  2. Dynamic Toast Types:

    $status = $request->wasSuccessful() ? 'success' : 'error';
    ToastMagic::$status('Operation Result', 'Details here.');
    
  3. Conditional Toast Dispatch:

    if ($this->shouldShowToast()) {
        $this->dispatch('toastMagic', [
            'status' => 'info',
            'title' => 'Note',
            'message' => 'This is a conditional toast.'
        ]);
    }
    
  4. Toast Templates:

    @toastMagic
        @slot('template')
            <div class="custom-toast">
                {{ $message }}
            </div>
        @endslot
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata