Weave 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

Flash Bundle Laravel Package

aretusa/flash-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require aretusa/flash-bundle
    

    Enable the bundle in AppKernel.php:

    new Aretusa\Bundle\FlashBundle\AretusaFlashBundle(),
    
  2. Publish Assets:

    php app/console assets:install web --symlink --relative
    
  3. Include in Layout: Add to your base template (base.html.twig or similar):

    {% block stylesheets %}
        <link href="{{ asset('bundles/aretusaflash/css/flash-message.css') }}" rel="stylesheet" />
    {% endblock %}
    
    {% block javascripts %}
        <script src="//code.jquery.com/jquery-2.1.3.min.js"></script>
        <script src="{{ asset('bundles/aretusaflash/js/flash-message.js') }}"></script>
        <script>
            $('#flash-messages').flashNotification('init');
        </script>
    {% endblock %}
    
  4. First Use Case: Add flash messages in a controller:

    $this->get('session')->getFlashBag()->add('success', 'Your action was successful!');
    

    For AJAX requests, messages will automatically appear in the JSON response.


Implementation Patterns

Core Workflow

  1. Flash Messages in Controllers: Use Symfony’s native FlashBag for both traditional and AJAX requests:

    // Traditional request (redirect)
    $this->get('session')->getFlashBag()->add('error', 'Invalid input!');
    return $this->redirectToRoute('home');
    
    // AJAX request (JSON response)
    $this->get('session')->getFlashBag()->add('success', 'Saved!');
    return new JsonResponse(['status' => 'ok']);
    
  2. AJAX Response Handling: The bundle automatically injects flash messages into JSON responses. No manual intervention required.

  3. Customizing Messages: Override the Twig template (flash-messages.html.twig) to modify appearance or behavior:

    {# app/Resources/AretusaFlashBundle/views/flash-messages.html.twig #}
    <div id="flash-messages">
        {% for type, messages in flashbag.getMessages() %}
            {% for message in messages %}
                <div class="flash-{{ type }}">{{ message }}</div>
            {% endfor %}
        {% endfor %}
    </div>
    
  4. Dynamic Initialization: Initialize flash notifications on page load or after AJAX calls:

    // Initialize on page load
    $(document).ready(function() {
        $('#flash-messages').flashNotification('init');
    });
    
    // Initialize after AJAX success
    $.ajax({
        url: '/submit',
        success: function() {
            $('#flash-messages').flashNotification('init');
        }
    });
    
  5. Integration with Forms: Use with Symfony’s form component for validation errors:

    if ($form->isSubmitted() && !$form->isValid()) {
        $this->get('session')->getFlashBag()->add('error', 'Please correct the errors below.');
    }
    

Gotchas and Tips

Pitfalls

  1. Missing jQuery: The bundle requires jQuery (flash-message.js depends on it). Ensure it’s loaded before flash-message.js.

  2. Asset Paths: If using Symfony Flex or custom asset paths, verify the bundle’s assets are correctly symlinked:

    php bin/console assets:install
    
  3. FlashBag Persistence: Flash messages are session-bound. For AJAX requests, ensure the session is active (e.g., cookies enabled).

  4. Template Overrides: Overriding flash-messages.html.twig requires the file to exist in:

    app/Resources/AretusaFlashBundle/views/flash-messages.html.twig
    

    Otherwise, the default template will be used.

  5. JSON Response Conflicts: If manually returning a JsonResponse, ensure flash messages are not cleared prematurely:

    // Bad: Clears flash messages before response
    $this->get('session')->getFlashBag()->clear();
    
    // Good: Let the bundle handle it
    return new JsonResponse(['data' => $data]);
    

Debugging Tips

  1. Check Console for Errors: If flash messages don’t appear, inspect the browser console for jQuery or JS errors.

  2. Verify FlashBag Contents: Debug flash messages in a controller:

    dump($this->get('session')->getFlashBag()->all());
    
  3. Inspect Network Requests: For AJAX calls, check the response headers/body for flash message inclusion.

  4. Clear Cache: After overriding templates or configurations, clear the cache:

    php bin/console cache:clear
    

Extension Points

  1. Custom Message Types: Extend the CSS classes in flash-messages.html.twig to support custom types (e.g., warning, info).

  2. Dynamic Message Placement: Modify flash-message.js to target a different DOM element:

    // Default: $('#flash-messages')
    // Custom: $('.custom-flash-container')
    $('.custom-flash-container').flashNotification('init');
    
  3. Localization: Localize messages by overriding the Twig template and using Symfony’s translation system:

    <div class="flash-{{ type }}">{{ message|trans }}</div>
    
  4. Server-Side Filtering: Filter flash messages before they’re added to the response (e.g., exclude certain types for AJAX):

    $flashBag = $this->get('session')->getFlashBag();
    $messages = $flashBag->get('error'); // Get specific type
    if ($messages && !$this->isAjax()) {
        $flashBag->add('error', $messages);
    }
    
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.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel