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

uxweb/sweet-alert

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require uxweb/sweet-alert
    

    For Laravel < 5.5, register the service provider and alias in config/app.php.

  2. Include SweetAlert.js:

    • CDN (quickest): Add to your main layout (e.g., resources/views/layouts/app.blade.php):
      <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
      @include('sweet::alert')
      
    • Laravel Mix (recommended for production):
      yarn add sweetalert --dev
      
      Require in resources/js/bootstrap.js:
      require("sweetalert");
      
  3. First use case: Trigger a success alert in a controller:

    use UxWeb\SweetAlert\Facades\Alert;
    
    public function showSuccess()
    {
        Alert::success('Success!', 'Your action was completed.');
        return redirect()->back();
    }
    

Implementation Patterns

Core Workflows

  1. Basic Alerts: Use facades for simplicity:

    Alert::success('Title', 'Message');
    Alert::error('Error', 'Something went wrong');
    Alert::warning('Warning', 'Be careful!');
    Alert::info('Info', 'Here is some info');
    
  2. Customizing Alerts: Pass an array for advanced options:

    Alert::success('Custom Alert', 'Message', [
        'timer' => 3000,
        'confirmButtonText' => 'Okay',
        'showConfirmButton' => false,
    ]);
    
  3. Conditional Alerts: Check for flash data or session variables:

    if (session()->has('success')) {
        Alert::success('Success', session('success'));
    }
    
  4. Integration with Forms: Trigger alerts after form submission:

    public function store(Request $request)
    {
        $validated = $request->validate([...]);
        Alert::success('Submitted', 'Your form was saved!');
        return back();
    }
    
  5. Dynamic Alerts: Use Blade directives for dynamic content:

    @alert(['title' => 'Dynamic', 'text' => 'User ' . $user->name . ' created'])
    
  6. Queueing Alerts: Store alerts in the session and display them on the next request:

    session()->flash('alert', ['type' => 'success', 'title' => 'Queued', 'text' => 'This will show later']);
    

Gotchas and Tips

Pitfalls

  1. Frontend Dependency:

    • Forgetting to include sweetalert.min.js or @include('sweet::alert') will result in no alerts appearing.
    • Fix: Always verify the CDN or Mix setup in your layout file.
  2. Session Flash Data: Alerts triggered via session()->flash() must be checked in the next request. Directly flashing alerts won’t work:

    // ❌ Won't work
    session()->flash('alert', Alert::success('Test', 'Message'));
    
    // ✅ Correct
    session()->flash('alert', ['type' => 'success', 'title' => 'Test', 'text' => 'Message']);
    
  3. Laravel Mix Caching: After adding SweetAlert via Mix, run:

    npm run dev
    

    Or for production:

    npm run prod
    

    To avoid stale JavaScript files.

  4. CSRF Conflicts: If alerts trigger unexpectedly, ensure no JavaScript errors exist (check browser console). SweetAlert may conflict with other libraries if not properly initialized.

  5. Deprecated Methods: Avoid using Alert::make() (if present in older versions). Stick to facades like Alert::success().


Debugging Tips

  1. Check the Console: Open browser dev tools (F12) to verify SweetAlert.js loads without errors. Look for:

    Uncaught ReferenceError: swal is not defined
    

    This indicates the CDN/Mix setup failed.

  2. Inspect Session Data: Dump session flash data to confirm alerts are being set:

    dd(session()->all());
    
  3. Test with Hardcoded Alerts: Temporarily hardcode an alert in your Blade file to isolate issues:

    <script>
        swal("Test", "If you see this, SweetAlert is working!");
    </script>
    

Extension Points

  1. Custom Alert Types: Extend the package by adding new alert types (e.g., Alert::question()). Override the SweetAlert facade or create a helper:

    if (!method_exists(\UxWeb\SweetAlert\Facades\Alert, 'question')) {
        Alert::macro('question', function ($title, $text, $options = []) {
            return $this->alert('question', $title, $text, $options);
        });
    }
    
  2. Theming: Customize SweetAlert’s appearance by overriding its CSS. Add to your main CSS file:

    .swal2-popup {
        background-color: #f8f9fa;
        color: #333;
    }
    
  3. Localization: Use SweetAlert’s built-in localization by including locale files and setting the language option:

    Alert::success('Title', 'Message', ['language' => 'es']);
    

    Ensure the locale file (e.g., sweetalert.js.es.js) is loaded via Mix or CDN.

  4. Event-Based Alerts: Trigger alerts based on Laravel events (e.g., Illuminate\Auth\Events\Registered):

    event(new Registered($user));
    Alert::success('Registered', 'Account created!');
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor