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

Livewire Swal Laravel Package

tuhin-su/livewire-swal

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require tuhin-su/livewire-swal
    

    Publish the config file (if available):

    php artisan vendor:publish --provider="TuhinSu\LivewireSwal\LivewireSwalServiceProvider"
    
  2. Basic Usage Import the package in your Livewire component:

    use TuhinSu\LivewireSwal\Facades\LivewireSwal;
    

    Trigger a simple alert in a Livewire method:

    public function showAlert()
    {
        LivewireSwal::fire([
            'title' => 'Success!',
            'text' => 'Your action was completed.',
            'type' => 'success'
        ]);
    }
    
  3. First Use Case Replace a basic alert() call in a Livewire component with LivewireSwal::fire() for a richer UI experience. Example:

    public function deleteItem($id)
    {
        LivewireSwal::fire([
            'title' => 'Confirm Deletion',
            'text' => 'Are you sure you want to delete this item?',
            'type' => 'warning',
            'showCancelButton' => true,
            'confirmButtonText' => 'Delete',
            'cancelButtonText' => 'Cancel',
            'reverseButtons' => true
        ], function () {
            // Perform deletion logic here
            $this->dispatch('item-deleted');
        });
    }
    

Implementation Patterns

Common Workflows

  1. Form Submissions Use SweetAlert2 for pre-submit confirmation or success/error feedback:

    public function submitForm()
    {
        LivewireSwal::fire([
            'title' => 'Submitting...',
            'text' => 'Please wait while we process your request.',
            'type' => 'info',
            'allowOutsideClick' => false,
            'showConfirmButton' => false
        ]);
    
        // Simulate async submission
        $this->dispatch('form-submitting');
    
        // After submission (e.g., in a callback or after redirect)
        LivewireSwal::fire([
            'title' => 'Success!',
            'text' => 'Your form was submitted successfully.',
            'type' => 'success'
        ]);
    }
    
  2. Event-Driven Alerts Trigger alerts based on Livewire events (e.g., mount, hydrate, or custom events):

    public function mount()
    {
        LivewireSwal::fire([
            'title' => 'Welcome!',
            'text' => 'Thanks for using our app.',
            'type' => 'info'
        ]);
    }
    
  3. Dynamic Alerts Pass dynamic data from Livewire to SweetAlert2:

    public function showUserAlert($user)
    {
        LivewireSwal::fire([
            'title' => 'User Update',
            'html' => 'Name: <strong>' . $user->name . '</strong><br>Email: ' . $user->email,
            'type' => 'info'
        ]);
    }
    
  4. Integration with Livewire Actions Combine with Livewire's wire:click or wire:model.live for real-time feedback:

    <button wire:click="showAlert" wire:loading.attr="disabled">
        Click Me
    </button>
    

Integration Tips

  • Customize SweetAlert2 Globally Override default options in config/livewire-swal.php:

    'defaults' => [
        'timer' => 1500,
        'showConfirmButton' => false,
        'allowOutsideClick' => false,
    ],
    
  • Reuse Alert Configs Define reusable alert types in your component:

    protected $alertConfigs = [
        'success' => ['type' => 'success', 'timer' => 2000],
        'error' => ['type' => 'error', 'timer' => 3000],
    ];
    
    public function showSuccess($message)
    {
        LivewireSwal::fire(array_merge($this->alertConfigs['success'], [
            'text' => $message
        ]));
    }
    
  • Handle Alert Responses Use callbacks to react to user actions (e.g., confirmations):

    LivewireSwal::fire([
        'title' => 'Delete?',
        'text' => 'This action cannot be undone.',
        'type' => 'warning'
    ], function () {
        $this->deleteRecord();
    }, function () {
        // User canceled
    });
    

Gotchas and Tips

Pitfalls

  1. Alert Stacking

    • Issue: Rapid calls to LivewireSwal::fire() may stack alerts.
    • Fix: Use LivewireSwal::close() or LivewireSwal::dismiss() to clear previous alerts before firing new ones:
      LivewireSwal::close();
      LivewireSwal::fire([...]);
      
  2. Livewire State Persistence

    • Issue: Alerts may not render if Livewire re-renders the component (e.g., due to wire:model updates).
    • Fix: Use wire:ignore on the SweetAlert2 container or trigger alerts in updated() hooks:
      public function updated($property)
      {
          if ($this->alertTriggered) {
              LivewireSwal::fire([...]);
              $this->alertTriggered = false;
          }
      }
      
  3. JavaScript Conflicts

    • Issue: SweetAlert2 may conflict with other JS libraries (e.g., jQuery plugins).
    • Fix: Ensure SweetAlert2 is loaded after other libraries or use LivewireSwal::init() to customize the initialization:
      LivewireSwal::init(['customContainer' => '#custom-swal-container']);
      
  4. Configuration Overrides

    • Issue: Global config in livewire-swal.php may not apply if not published.
    • Fix: Publish the config file and verify settings:
      php artisan vendor:publish --provider="TuhinSu\LivewireSwal\LivewireSwalServiceProvider" --tag="config"
      

Debugging Tips

  • Check for Errors Inspect the browser console for SweetAlert2 or Livewire errors. Common culprits:

    • Missing wire:key in alerts.
    • Conflicting jQuery or Bootstrap JS versions.
  • Verify Livewire Events Ensure alerts are triggered in the correct Livewire lifecycle method (e.g., mount vs. updated).

  • Inspect the DOM Confirm SweetAlert2's modal is rendered in the DOM. If not, check for JS errors or missing dependencies.

Extension Points

  1. Custom Alert Types Extend the package by adding methods for domain-specific alerts:

    public function showError($message, $details = null)
    {
        $config = [
            'title' => 'Error',
            'text' => $message,
            'type' => 'error',
            'timer' => 5000
        ];
    
        if ($details) {
            $config['html'] = '<p>' . $message . '</p><pre>' . print_r($details, true) . '</pre>';
        }
    
        LivewireSwal::fire($config);
    }
    
  2. Integration with Livewire Notifications Combine with wire:notify for a unified feedback system:

    public function showNotification()
    {
        $this->dispatch('alert', type: 'success', message: 'Action completed!');
        LivewireSwal::fire([
            'title' => 'Success',
            'text' => 'Action completed!',
            'type' => 'success'
        ]);
    }
    
  3. Localization Support Add language support by extending the package's config:

    'lang' => [
        'en' => [
            'title' => 'Message',
            'confirm' => 'OK',
            'cancel' => 'Cancel'
        ],
        'es' => [
            'title' => 'Mensaje',
            'confirm' => 'Aceptar',
            'cancel' => 'Cancelar'
        ]
    ],
    
  4. Testing Alerts Mock SweetAlert2 in PHPUnit tests:

    public function testAlertFires()
    {
        $this->expectsEvents(LivewireSwal::class);
        LivewireSwal::shouldReceive('fire')->once();
        $this->call('showAlert');
    }
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle