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 package to integrate SweetAlert2 popups: stylish alerts, confirmations, toasts, and notifications. Trigger from controllers or views with simple helpers and session flashes, customize options, and improve UX with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Alert

  1. Installation:

    composer require realrashid/sweet-alert
    

    Publish assets (optional, for custom themes):

    php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider"
    
  2. First Usage (in a controller):

    use RealRashid\SweetAlert\Facades\Alert;
    
    public function showSuccess()
    {
        Alert::success('Success!', 'Your action was completed successfully.');
    }
    
  3. Blade Integration: Add @include('sweetalert::alert') to your layout file (e.g., resources/views/layouts/app.blade.php).


First Use Case: Form Submission Feedback

// In your controller
public function store(Request $request)
{
    try {
        // Process form data
        Alert::success('Submitted!', 'Your form was submitted successfully.');
    } catch (\Exception $e) {
        Alert::error('Error!', 'Failed to submit: ' . $e->getMessage());
    }
}

Implementation Patterns

1. Facade vs Helper Methods

  • Facade (recommended for controllers):
    Alert::success('Title', 'Message');
    
  • Helper (for Blade templates):
    alert()->warning('Title', 'Message');
    

2. Dynamic Alerts with User Input

public function updateProfile(Request $request)
{
    $validated = $request->validate([...]);

    Alert::success('Profile Updated', "Your profile has been updated with {$request->name}.")
         ->timerProgressBar(); // Show progress bar
}

3. Confirmation Dialogs

public function deletePost($id)
{
    Alert::question('Delete Post?', 'Are you sure you want to delete this post?', function () {
        Post::find($id)->delete();
        return redirect()->back()->with('success', 'Post deleted!');
    });
}

4. Customizing Alerts

Alert::alert('Custom Alert', 'Message')
     ->position('top-center')
     ->timer(3000)
     ->showConfirmButton()
     ->focusConfirm();

5. Themes in Middleware

// app/Http/Middleware/SetTheme.php
public function handle($request, Closure $next)
{
    if (auth()->check() && auth()->user()->prefers_dark_mode) {
        config(['sweetalert.theme' => 'dark']);
    }
    return $next($request);
}

6. Toasts for Non-Intrusive Feedback

// In a controller
toast('Saved!', 'success');

// Or with custom position
toast('Updated!', 'info')->position('top-left');

Gotchas and Tips

Pitfalls

  1. Missing @include('sweetalert::alert'):

    • Alerts won’t render if the Blade directive is omitted. Add it to your layout file.
  2. Facade Not Found:

    • Ensure the SweetAlertServiceProvider is registered in config/app.php under providers.
  3. Theme Not Applying:

    • Verify .env has SWEET_ALERT_THEME=your-theme or use config(['sweetalert.theme' => 'dark']) in a service provider.
  4. JavaScript Errors:

    • If SweetAlert2 fails to load, check:
      • The CDN URL in config/sweetalert.php is correct.
      • No other scripts are conflicting (e.g., jQuery versions).
  5. Laravel 12+ Facade Issues:

    • After updating, clear the config cache:
      php artisan config:clear
      

Debugging Tips

  1. Check Console for Errors:

    • Open browser dev tools (F12) to see if SweetAlert2 scripts load without errors.
  2. Inspect Rendered HTML:

    • Look for <script> tags with sweetalert2 in the footer. If missing, the package isn’t publishing assets.
  3. Verify Config:

    // Dump current config
    dd(config('sweetalert'));
    
  4. Test Toast Position:

    • Default is bottom-right. Override globally in config/sweetalert.php or per-call:
      toast('Message', 'success')->position('top-center');
      

Extension Points

  1. Custom Themes:

    • Publish assets and override resources/views/vendor/sweetalert/themes/your-theme.blade.php.
  2. Middleware for Global Alerts:

    // app/Http/Middleware/ShowValidationErrors.php
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ($response->getStatusCode() === 422) {
            Alert::error('Validation Error', 'Please fix the errors below.');
        }
        return $response;
    }
    
  3. Dynamic Icons:

    Alert::alert('Title', 'Message', 'custom')
         ->iconHtml('<i class="fas fa-rocket"></i>');
    
  4. Localization:

    • Override SweetAlert2’s language files by publishing assets and modifying: resources/lang/vendor/sweetalert/.
  5. Conditional Alerts:

    if ($user->isAdmin()) {
        Alert::success('Admin Action', 'Only admins can perform this action.');
    }
    

Pro Tips

  • Use confirmDelete for CRUD:
    Alert::confirmDelete('Delete User?', 'user.id', 'users', function () {
        return redirect()->route('users.index');
    });
    
  • Chain Methods:
    Alert::alert('Title', 'Message')
         ->timer(5000)
         ->showCloseButton()
         ->reverseButtons();
    
  • Disable Middleware Alerts: Set SWEET_ALERT_MIDDLEWARE=false in .env to bypass middleware-triggered alerts.
  • Leverage html() for Rich Content:
    Alert::html('HTML Alert', '<strong>Bold</strong> and <a href="#">links</a> supported.', 'info');
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport