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

Sweet Alert Laravel Package

realrashid/sweet-alert

Laravel wrapper for SweetAlert2 that makes it easy to show stylish alert, toast, and confirmation dialogs. Flash messages from controllers or middleware, with helpers for success/error/warning/info, custom options, and Blade support for quick integration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require realrashid/sweet-alert
    

    Publish the config (optional but recommended):

    php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider" --tag="config"
    
  2. Load Assets: Add to your resources/views/layouts/app.blade.php (or equivalent):

    @include('sweetalert::alert')
    
  3. First Usage: In a controller or route:

    use RealRashid\SweetAlert\Facades\Alert;
    
    // Basic success alert
    Alert::success('Success!', 'Your action was completed.');
    

    Or in Blade:

    @alert('success', 'Success!', 'Your action was completed.')
    

First Use Case: Form Submission Feedback

// In your controller
public function store(Request $request) {
    $validated = $request->validate([...]);

    try {
        // Save data
        Alert::success('Record saved', 'Your data has been saved successfully.');
    } catch (\Exception $e) {
        Alert::error('Error', 'Failed to save data: ' . $e->getMessage());
    }

    return back();
}

Implementation Patterns

Controller Integration

Flash Messaging Pattern:

// Redirect with flash alert
return redirect()->route('dashboard')
    ->withSuccess('Profile updated', 'Your profile has been updated successfully.');

Dynamic Alerts:

// Conditional alerts
if ($user->exists) {
    Alert::success('User created', 'New user added to the system.');
} else {
    Alert::error('Error', 'Failed to create user.');
}

Blade Integration

Reusable Alert Components:

<!-- resources/views/components/alert.blade.php -->
@if(session('success'))
    @alert('success', session('success.title'), session('success.message'))
@endif

Inline Alerts:

@alert('warning', 'Confirm Action',
    'Are you sure you want to delete this item?',
    ['showConfirmButton' => true, 'showCancelButton' => true]
)

Middleware for Global Alerts

// app/Http/Middleware/HandleInertiaRequests.php
public function terminate($request, $response) {
    if ($response->getStatusCode() === 404) {
        Alert::warning('Page Not Found', 'The requested resource could not be found.');
    }
}

Toast Notifications

// In a controller
Alert::toast('New Message', 'You have a new notification', 'top-right');

// With custom styling
Alert::toast('Update Available', 'A new version is ready!')
    ->timerProgressBar()
    ->position('top-left');

Confirmation Dialogs

// In Blade
@alert('question', 'Delete Item',
    'Are you sure you want to delete this item?',
    [
        'showConfirmButton' => true,
        'showCancelButton' => true,
        'confirmButtonText' => 'Delete',
        'cancelButtonText' => 'Cancel',
        'reverseButtons' => true,
        'focusConfirm' => false,
        'focusCancel' => true,
        'preConfirm' => 'return confirm("This action cannot be undone.")'
    ]
)

Theming and Styling

// In config/sweet-alert.php
'theme' => 'dark', // or 'light', 'custom'

// Custom CSS classes
Alert::success('Title', 'Message')
    ->customClass('custom-alert')
    ->width('400px')
    ->padding('2rem');

Gotchas and Tips

Common Pitfalls

  1. Missing Assets:

    • If alerts don't appear, ensure @include('sweetalert::alert') is in your layout.
    • Verify the JS is loaded (check browser console for 404 errors).
  2. Facade Not Found:

    • After updating Laravel, run:
      composer dump-autoload
      php artisan optimize:clear
      
  3. Configuration Overrides:

    • Global config in config/sweet-alert.php may override per-alert settings. Use config() helper to check:
      $defaultPosition = config('sweet-alert.default_toast_position');
      
  4. Blade Compilation Issues:

    • If using @alert in Blade, escape dynamic content:
      @alert('success', '{{ $title }}', '{{ $message }}')
      

Debugging Tips

  • Check Console: SweetAlert2 logs errors to the browser console. Look for:

    Uncaught ReferenceError: Swal is not defined
    

    (Fix: Ensure JS is loaded before usage.)

  • IDE Support: Use @method PHPDoc annotations (added in v7.3.2) for autocompletion:

    Alert::success('Title', 'Message')->timer(3000);
    

Performance Considerations

  • Lazy Loading: Set 'load_js' => 'auto' in config to load SweetAlert only when needed.
  • CDN vs Bundled: Use CDN for production ('cdn' => true) to reduce asset size.

Extension Points

  1. Custom Methods: Create a macro in a service provider:

    Alert::macro('customAlert', function($title, $message) {
        return $this->success($title, $message)
            ->timerProgressBar()
            ->customClass('my-custom-alert');
    });
    
  2. Middleware Integration: Extend the SweetAlertMiddleware to add custom logic:

    public function handle($request, Closure $next) {
        if ($request->wantsJson()) {
            Alert::json('Info', 'This is a JSON response.');
        }
        return $next($request);
    }
    
  3. Theming System: Override default themes by publishing assets:

    php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider" --tag="public"
    

    Then modify public/vendor/sweetalert/css/sweetalert2.css.

Laravel-Specific Quirks

  • Flash Data Persistence: Flash alerts persist only for the next request. For multi-step forms, use sessions:

    session(['alert' => ['type' => 'success', 'title' => 'Title', 'message' => 'Message']]);
    
  • Livewire/Alpine Integration: Trigger alerts from frontend:

    // Alpine.js
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('alerts', () => ({
                showSuccess() {
                    @this.$wire.emit('showAlert', {
                        type: 'success',
                        title: 'Success',
                        message: 'Action completed'
                    });
                }
            }));
        });
    </script>
    

    In Livewire:

    public function showAlert($data) {
        Alert::success($data['title'], $data['message']);
    }
    
  • Testing: Mock alerts in PHPUnit:

    $this->expectsEvents(AlertEvent::class);
    Alert::success('Test', 'Message');
    $this->assertEventDispatched(AlertEvent::class);
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai