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 assets (optional, if using custom themes or CDN):

    php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider"
    
  2. First Use Case: Trigger a success alert in a controller:

    use RealRashid\SweetAlert\Facades\Alert;
    
    public function store(Request $request) {
        Alert::success('Success!', 'Your data has been saved.');
        return back();
    }
    
  3. Where to Look First:

    • config/sweetalert.php (default config, themes, CDN settings)
    • resources/views/vendor/sweetalert/ (published views)
    • SweetAlert2 Docs (for advanced customization)

Implementation Patterns

Core Workflows

1. Basic Alerts

// Facade
Alert::error('Error', 'Something went wrong.');
Alert::warning('Warning', 'This action cannot be undone.');

// Helper
alert()->info('Info', 'This is an informational message.');

2. Conditional Alerts

public function update(Request $request, $id) {
    try {
        $model = Model::findOrFail($id);
        $model->update($request->all());
        alert()->success('Updated', 'Record updated successfully.');
    } catch (\Exception $e) {
        alert()->error('Error', $e->getMessage());
    }
    return back();
}

3. Dynamic Alerts with Data

public function show($id) {
    $model = Model::findOrFail($id);
    Alert::info(
        'User Details',
        "Name: {$model->name}<br>Email: {$model->email}",
        'html'
    );
    return view('profile');
}

4. Toasts (Non-Intrusive)

// Default position (configurable)
toast('Saved!', 'success');

// Custom position
toast('Updated!', 'info')->position('top-right');

5. Confirmation Dialogs

public function destroy($id) {
    Alert::question(
        'Delete Confirmation',
        'Are you sure you want to delete this item?',
        function () {
            Model::destroy($id);
            toast('Deleted!', 'success');
        },
        function () {
            toast('Cancelled', 'info');
        }
    );
    return back();
}

Integration Tips

1. Middleware for Global Alerts

Create a middleware to flash alerts on redirect:

// app/Http/Middleware/AlertMiddleware.php
public function handle($request, Closure $next) {
    if ($request->session()->has('alert')) {
        $alert = $request->session()->get('alert');
        Alert::make($alert['type'], $alert['title'], $alert['message']);
        $request->session()->forget('alert');
    }
    return $next($request);
}

2. Blade Directives

Create a custom Blade directive for reusable alerts:

// app/Providers/BladeServiceProvider.php
Blade::directive('alert', function ($expression) {
    return "<?php echo RealRashid\SweetAlert\Facades\Alert::make($expression); ?>";
});

Usage:

@alert(['success', 'Title', 'Message'])

3. API Responses with Alerts

For API responses, use Laravel's response()->json() with a meta field:

return response()->json([
    'success' => false,
    'message' => 'Validation failed',
    'errors' => $validator->errors(),
    'meta' => [
        'alert' => ['error', 'Validation Error', 'Please check the form.'],
    ]
]);

4. Theming Across the App

Set a default theme in .env:

SWEET_ALERT_THEME=bootstrap-4

Or override per alert:

Alert::make('success', 'Title', 'Message')->theme('material-ui');

5. Customizing SweetAlert2

Extend the package by publishing assets and modifying:

php artisan vendor:publish --tag=sweetalert-assets

Edit resources/views/vendor/sweetalert/sweetalert.blade.php to add custom options.


Gotchas and Tips

Pitfalls

  1. Facade vs Helper Confusion:

    • Facade: Alert::success('Title', 'Message')
    • Helper: alert()->success('Title', 'Message')
    • Gotcha: Mixing these can cause unexpected behavior if chaining methods.
  2. Session Flashing:

    • Alerts triggered via session()->flash() won’t work directly. Use middleware or redirect with with():
      return redirect()->route('home')->with([
          'alert' => ['success', 'Success', 'Operation completed.'],
      ]);
      
  3. CDN Loading Issues:

    • If using CDN, ensure the URL is correct in config/sweetalert.php. Test with:
      Alert::cdn('https://cdn.jsdelivr.net/npm/sweetalert2@11');
      
  4. Theme Overrides:

    • Themes set in .env apply globally. Override per alert with:
      Alert::make('Title', 'Message')->theme('dark');
      
  5. JavaScript Conflicts:

    • If SweetAlert2 doesn’t render, check for duplicate script inclusions. Use the package’s middleware to auto-load scripts:
      // config/sweetalert.php
      'auto_load' => true,
      

Debugging Tips

  1. Check Published Assets:

    • Verify public/vendor/sweetalert/ exists after publishing assets. Clear cache if missing:
      php artisan view:clear
      php artisan cache:clear
      
  2. Inspect Network Requests:

    • Open DevTools (F12) and check if SweetAlert2 scripts are loaded. Look for 404 errors.
  3. Log Alert Config:

    • Temporarily log the alert config to debug:
      Alert::success('Title', 'Message');
      \Log::debug('SweetAlert Config:', [
          'config' => \RealRashid\SweetAlert\Facades\Alert::getConfig(),
      ]);
      
  4. Disable Middleware:

    • Temporarily disable the SweetAlert middleware to isolate issues:
      // app/Http/Kernel.php
      protected $middleware = [
          // Remove or comment out:
          // \RealRashid\SweetAlert\Middleware\SweetAlertMiddleware::class,
      ];
      

Extension Points

  1. Custom Alert Types: Create a new alert type by extending the ToSweetAlert class:

    // app/Extensions/CustomAlert.php
    namespace App\Extensions;
    
    use RealRashid\SweetAlert\ToSweetAlert;
    
    class CustomAlert extends ToSweetAlert {
        public function custom($title, $message) {
            $this->title = $title;
            $this->text = $message;
            $this->type = 'custom';
            $this->timer = 10000;
            return $this;
        }
    }
    

    Register in SweetAlertServiceProvider:

    $this->app->bind('custom.alert', function () {
        return new \App\Extensions\CustomAlert();
    });
    
  2. Dynamic Themes: Fetch themes dynamically from a database:

    $theme = Theme::find($request->theme_id)->name;
    Alert::make('Title', 'Message')->theme($theme);
    
  3. Event-Based Alerts: Trigger alerts on events:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'user.created' => [
            function ($user) {
                Alert::success('User Created', "Welcome, {$user->name}!");
            },
        ],
    ];
    
  4. Localization: Override SweetAlert2’s text via config:

    // config/sweetalert.php
    'text' => [
        'confirm' => 'Are you sure?',
        'cancel' => 'Cancel',
        'ok' => 'OK',
    ],
    
  5. Performance Optimization:

    • Disable auto-loading in production if not needed:
      // config/sweetalert.php
      'auto_load' => env('APP_ENV') !== 'production',
      
    • Lazy-load SweetAlert2 scripts only on pages needing alerts.
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