Toast Notifications in Bagisto: The Complete Guide

Bagisto Toaster Notification

Toast notifications are essential for providing user feedback in web applications. In Bagisto, the popular Laravel-based e-commerce framework, toast notifications follow a specific pattern that differs from many other frameworks. This comprehensive guide covers both perspectives: showing toast notifications from Vue.js components for immediate client-side feedback, and triggering them from Laravel controllers using session flash messages for server-side operations.

🍞 Bagisto’s Front-end Toast System

Bagisto uses a custom event-driven toast notification system built on Vue.js. The system consists of:

  1. Flash Group Component: Handles display and animations
  2. Event Emitter: Triggers notification events
  3. Auto-dismiss: Automatically removes notifications after a few seconds

Basic Implementation

When you’re trying to notify the user from a Vue component, this is the way of doing it using built-in toaster displaying feature.

// ✅ CORRECT - Use $emitter.emit()
this.$emitter.emit('add-flash', {
    type: 'success',
    message: 'Operation completed successfully!'
});

Available Notification Types

// Success notification (green)
this.$emitter.emit('add-flash', {
    type: 'success',
    message: 'Data saved successfully!'
});

// Error notification (red)
this.$emitter.emit('add-flash', {
    type: 'error',
    message: 'Something went wrong!'
});

// Warning notification (yellow/orange)
this.$emitter.emit('add-flash', {
    type: 'warning',
    message: 'Please review your input!'
});

// Info notification (blue)
this.$emitter.emit('add-flash', {
    type: 'info',
    message: 'New update available!'
});

Here is a sample output (Click on the image if GIF is not playing) :

You may check the source code of the above testing in this gist.

❌ Common Mistakes to Avoid

Wrong Method Names

// ❌ WRONG - These don't exist in Bagisto
this.$toast.add({...});           // Not available
this.$toast.success('message');   // Not available
this.$notify({...});              // Not available

Missing Layout Component

If your custom page doesn’t include the admin layout, you need to manually include the flash-group component:

<!-- Make sure this is included in your layout -->
<x-admin::flash-group />

🛠️ Practical Examples

AJAX Success/Error Handling

// saveData() is a method in your Vue component
async saveData() {
    try {
        const response = await this.$axios.post('/api/save-data', this.formData);

        if (response.data.success) {
            this.$emitter.emit('add-flash', {
                type: 'success',
                message: response.data.message || 'Data saved successfully!'
            });
        } else {
            this.$emitter.emit('add-flash', {
                type: 'error',
                message: response.data.message || 'Failed to save data'
            });
        }
    } catch (error) {
        console.error('Error:', error);
        this.$emitter.emit('add-flash', {
            type: 'error',
            message: 'An unexpected error occurred'
        });
    }
}

Form Validation Feedback

// validateForm() is a method in your Vue component
validateForm() {
    if (!this.email) {
        this.$emitter.emit('add-flash', {
            type: 'warning',
            message: 'Email field is required'
        });
        return false;
    }

    if (!this.isValidEmail(this.email)) {
        this.$emitter.emit('add-flash', {
            type: 'error',
            message: 'Please enter a valid email address'
        });
        return false;
    }

    return true;
}

Bulk Operations

// processBulkAction() is a method in your Vue component
async processBulkAction(selectedItems) {
    this.$emitter.emit('add-flash', {
        type: 'info',
        message: `Processing ${selectedItems.length} items...`
    });

    try {
        const response = await this.$axios.post('/api/bulk-update', {
            items: selectedItems
        });

        this.$emitter.emit('add-flash', {
            type: 'success',
            message: `Successfully updated ${response.data.updated_count} items`
        });
    } catch (error) {
        this.$emitter.emit('add-flash', {
            type: 'error',
            message: 'Bulk operation failed'
        });
    }
}

🔄 Backend Flash Messages: The Laravel Way

While the Vue.js approach is perfect for client-side interactions, sometimes you need to show notifications after server-side operations like form submissions, redirects, or AJAX responses. Bagisto seamlessly integrates Laravel’s session flash messaging with its toast notification system. This process includes 2 steps:

1. Setting Flash Messages from Controllers

<?php
// Set Laravel flash messages from the backend (i.e., Controller)

// Success message
session()->flash('success', 'Product created successfully!');

// And Then send the user back
return redirect()->back()->withInput();
// Or to specific route
return redirect()->route('admin.products.index');

2. Display Flash Message on the next page load

Bagisto automatically converts Laravel flash messages into toast notifications. The magic happens in the layout through this Blade component:

<!-- This component automatically reads session flash data -->
<x-admin::flash-group />

The flash-group component checks for session flash messages and automatically emits the appropriate Vue.js events:

{{-- Simplified view of what happens internally --}}
@if (session()->has('success'))
    <script>
        window.flashMessages = window.flashMessages || [];
        window.flashMessages.push({
            type: 'success',
            message: '{{ session('success') }}'
        });
    </script>
@endif

Flash Message Types and Styling

Bagisto supports these flash message types from the backend:

<?php
// All of these automatically become styled toast notifications
session()->flash('success', 'Green toast with checkmark icon');
session()->flash('error', 'Red toast with error icon');
🔗()->flash('warning', 'Yellow/orange toast with warning icon');
session()->flash('info', 'Blue toast with info icon');

// You can also use Laravel's with() method
return redirect()->route('admin.dashboard')
    ->with('success', 'Welcome back!')
    ->with('info', 'You have 3 new notifications');

🔗 Combining Frontend and Backend Approaches

You can use both approaches together for comprehensive user feedback. In this approach,

  • If an action was successful, set session flash and respond with redirect instruction. From frontend, redirect to the instructed route on success response.
  • Otherwise, avoid page loading and show frontend toast notification to inform the failure.
// Handle AJAX form submission
async submitForm() {
    try {
        const response = await this.$axios.post('/api/products', this.formData);

        if (response.data.success) {
            // Backend sets session flash
            // Redirect will show the backend flash message
            if (response.data.redirect) {
                window.location.href = response.data.redirect;
            }
        }

    } catch (error) {
        // Show immediate error feedback
        this.$emitter.emit('add-flash', {
            type: 'error',
            message: 'Submission failed. Please try again.'
        });
    }
}

🎨 Visual Behavior

Bagisto’s toast notifications:

  • Appear in the top-right corner of the screen
  • Slide in from the right with smooth animations
  • Auto-dismiss after approximately 3-5 seconds
  • Stack vertically if multiple notifications are triggered
  • Include appropriate icons based on the type
  • Support both light and dark modes

🔧 Architecture Deep Dive

Event Flow

  1. Component calls this.$emitter.emit('add-flash', {...})
  2. Flash Group component listens for ‘add-flash’ events
  3. Notification is added to the display queue
  4. Vue transitions handle the visual animations
  5. Auto-removal timer starts

Layout Integration

<!-- In packages/Webkul/Admin/src/Resources/views/components/layouts/index.blade.php -->
<div id="app" class="h-full">
    <!-- Flash Message Blade Component -->
    <x-admin::flash-group />

    <!-- Rest of your content -->
</div>

👍🏼 Best Practices

  1. Keep messages concise – Users should be able to read them quickly
  2. Use appropriate types – Match the severity with the notification type
  3. Provide actionable feedback – Tell users what happened and what to do next
  4. Don’t overuse – Too many notifications can be annoying
  5. Test thoroughly – Ensure notifications work across different scenarios

🚀 Conclusion

Bagisto provides a comprehensive toast notification system that works seamlessly from both frontend and backend perspectives. The key is understanding when to use each approach:

Frontend Approach (Vue.js)

  • Use this.$emitter.emit('add-flash', {...}) for immediate client-side feedback
  • Perfect for AJAX responses, form validation, and interactive features
  • Provides instant user feedback without page refreshes

Backend Approach (Laravel Flash Messages)

  • Use session()->flash('type', 'message') for server-side operations
  • Ideal for form submissions, redirects, and traditional page loads
  • Automatically converted to styled toast notifications

Key Takeaways

  • Ensure the flash-group component is included in your layout for both approaches to work
  • Choose appropriate notification types (success, error, warning, info) for better UX
  • Handle both success and error cases in your applications
  • Combine both approaches when needed for comprehensive user feedback
  • Keep messages concise and actionable regardless of the source

With this comprehensive understanding, you can now implement professional, consistent toast notifications throughout your Bagisto applications, whether triggered from the frontend or backend!


Found this helpful? Share it with other Laravel / Bagisto developers and contribute to the community! 🎉

Leave a Comment

Your email address will not be published. Required fields are marked *