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

Toast Bundle Laravel Package

asmitta-01/toast-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package** via Composer:
   ```bash
   composer require asmitta-01/toast-bundle
  1. Enable the bundle in config/bundles.php (if not using Flex):
    return [
        Asmitta\ToastBundle\AsmittaToastBundle::class => ['all' => true],
    ];
    
  2. Configure the bundle by creating config/packages/asmitta_toast.yaml (default config is auto-generated):
    asmitta_toast:
      toast_container:
        position: bottom-center
      toast_item:
        timer: 5000
        progress_bar: false
    
  3. Include CSS assets in your base template (e.g., base.html.twig):
    <link href="{{ asset('bundles/asmittaToast/css/toast.css') }}" rel="stylesheet">
    
  4. Render toasts in your template:
    {{ render_toasts() }}
    

First Use Case

Trigger a flash message in a controller and render it as a toast:

// src/Controller/SomeController.php
use Asmitta\ToastBundle\Enum\ToastType;

public function successAction(): Response
{
    $this->addFlash('success', 'Operation completed successfully!');
    return $this->render('some_template.html.twig');
}

The toast will appear automatically when the page loads.


Implementation Patterns

Controller Integration

  • Standard Flash Messages: Use Symfony’s built-in addFlash() with predefined types (success, error, warning, info):
    $this->addFlash('success', 'User created!');
    $this->addFlash('error', 'Validation failed.');
    
  • Custom Toast Types: Use the ToastType enum for explicit control:
    $this->addFlash(ToastType::SUCCESS->value, 'Custom success message');
    
  • Dynamic Messages: Pass variables to templates via flash data:
    $this->addFlash('info', ['message' => 'Data saved', 'count' => 3]);
    
    Access in Twig:
    {% for message in flashbag('info') %}
        {{ message.message }} ({{ message.count }} items)
    {% endfor %}
    

Template Customization

  • Override Default Template: Extend the default template (@AsmittaToast/toast_items/default.html.twig) in your project:
    {% extends '@AsmittaToast/toast_items/default.html.twig' %}
    {% block toast_content %}
        {{- parent() -}}
        <div class="custom-addon">Extra content</div>
    {% endblock %}
    
  • Use Icon Templates: For visual cues, switch to with_icon or colored_icon templates (requires Bootstrap Icons):
    # config/packages/asmitta_toast.yaml
    asmitta_toast:
      toast_item:
        template: '@AsmittaToast/toast_items/with_icon.html.twig'
    
    Include Bootstrap Icons in your template:
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    

Configuration Workflows

  • Positioning: Adjust toast placement dynamically (e.g., for modals):
    # config/packages/asmitta_toast.yaml
    asmitta_toast:
      toast_container:
        position: top-right  # Overrides default
    
  • Auto-Hide: Disable or extend timer per environment:
    # config/packages/asmitta_toast.yaml (dev)
    asmitta_toast:
      toast_item:
        timer: 0  # Disable auto-hide in dev
    
  • Max Toasts: Limit UI clutter:
    asmitta_toast:
      toast_container:
        max_toasts: 3  # Max 3 toasts per type
    

Event-Driven Extensions

  • Listen for Toast Events: Extend functionality via Symfony events (e.g., modify messages before rendering):
    // src/EventListener/ToastListener.php
    use Asmitta\ToastBundle\Event\ToastEvent;
    
    public function onToastRender(ToastEvent $event): void
    {
        $message = $event->getMessage();
        if (str_contains($message, 'error')) {
            $event->setMessage('Custom error: ' . $message);
        }
    }
    
    Register the listener in services.yaml:
    services:
        App\EventListener\ToastListener:
            tags:
                - { name: kernel.event_listener, event: asmitta.toast.render, method: onToastRender }
    

Gotchas and Tips

Common Pitfalls

  1. Missing Assets:

    • Symptom: Toasts appear but lack styling.
    • Fix: Ensure assets:install is run and CSS files are included in the template.
    • Debug: Check the network tab for 404s on /bundles/asmittaToast/css/....
  2. Flash Bag Not Clearing:

    • Symptom: Toasts persist across requests.
    • Fix: Symfony’s flash messages are request-scoped by default. If using AJAX, manually clear the bag:
      $this->get('session')->getFlashBag()->clear();
      
  3. Template Overrides Not Working:

    • Symptom: Custom template changes are ignored.
    • Fix: Ensure the template path in config/packages/asmitta_toast.yaml is correct and the template extends the base template properly.
  4. Bootstrap Icons Missing:

    • Symptom: Icon templates show broken icons.
    • Fix: Include the Bootstrap Icons CDN in your layout (required for with_icon/colored_icon templates).
  5. Symfony 8 Session Issues:

    • Symptom: Flash messages fail to render.
    • Fix: Update to ToastBundle v0.4.0+ (includes Symfony 8 session compatibility fixes).

Debugging Tips

  • Inspect Flash Bag: Dump flash messages in a template to verify they’re set:
    {% for type, messages in app.flashbag.getAll() %}
        {{ dump(messages) }}
    {% endfor %}
    
  • Check Config: Validate asmitta_toast.yaml is loaded:
    php bin/console debug:config asmitta_toast
    
  • Override CSS: Use browser dev tools to inspect .asmitta-toast classes if styling is off.

Performance Considerations

  • Auto-Hide Timer: Set timer: 0 for critical messages (e.g., modals) to avoid accidental dismissal.
  • Max Toasts: Use max_toasts to prevent memory leaks from excessive flash messages (e.g., in loops).

Extension Points

  1. Custom Toast Types: Extend the ToastType enum and update the config to map new types:

    // src/Enum/CustomToastType.php
    namespace App\Enum;
    use Asmitta\ToastBundle\Enum\ToastType;
    
    enum CustomToastType: string {
        case INFO = 'info';
        case NOTICE = 'notice'; // New type
    }
    

    Update the template to handle the new type.

  2. Dynamic Positioning: Override the container position per route via a Twig function:

    {% set toast_position = 'top-right' if app.request.attributes.get('_route') == 'admin_dashboard' %}
    

    (Requires custom Twig extension to pass position to the bundle.)

  3. AJAX Support: Render toasts dynamically via JavaScript:

    // After AJAX success
    $.post('/update', data, function() {
        location.reload(); // Reload to render toasts (simplest approach)
        // OR fetch and append toasts via API endpoint
    });
    

Configuration Quirks

  • Null Values: max_toasts: null disables limits entirely (not 0).
  • Timer Units: Always use milliseconds (e.g., 5000 = 5 seconds).
  • Template Paths: Use absolute paths (e.g., @App/toast/custom.html.twig) for custom templates.

Migration Notes

  • From Bootstrap Toasts: Replace toast class with asmitta-toast (v0.4.0 breaking change). Update any custom CSS targeting .toast to use .asmitta-toast.
  • From Other Bundles: Remove conflicting toast-related CSS/JS (this bundle is standalone).

---
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