Palestinian Flag Solidarity with Palestine. We seek justice and peace, and strongly oppose all forms of injustice and genocide.
Enjoying PHPFlasher? Show your support with a star on GitHub! It helps others discover this tool and motivates us to keep improving it. Thank you

Requirements

PHPFlasher works seamlessly with Livewire v3, bringing dynamic flash notifications to your reactive components.

Required

PHP Version

v8.2 or higher
Required

Livewire

v3.0 or higher

Using older PHP or Livewire versions?

If you need to use PHP < v8.2 or Livewire < v3.0, use PHPFlasher v1 instead. It supports PHP ≥ v5.3 and earlier Livewire versions. Check out the v1 documentation here .

Installation

To use PHPFlasher with Livewire, follow the same installation steps as in the Laravel Installation guide.

Terminal
Installation
Livewire Installation
composer require php-flasher/flasher-laravel

After installing, run this command to set up the required assets:

Terminal
Setup Assets
php artisan flasher:install

Zero Configuration for Livewire

PHPFlasher automatically integrates with Livewire. No additional configuration needed - flash notifications work instantly across component updates and page refreshes.

Usage

Using PHPFlasher in Livewire components is simple. Just call the flash() helper function in your component methods.

Basic Usage

Dispatch notifications from your Livewire components:

UserComponent.php
<?php

namespace App\Livewire;

use Livewire\Component;

class UserComponent extends Component
{
    public function save()
    {
        // Save user logic here...

        // Show success notification
        flash()->success('User saved successfully!');
    }

    public function render()
    {
        return view('livewire.user');
    }
}

Pro Tip: Notifications Persist Across Livewire Updates

PHPFlasher automatically handles Livewire component updates and page refreshes. Notifications will display correctly even during partial page updates.

Complete Component Example

Here's a more complete example of a Livewire component with form handling and notifications:

ContactForm.php
<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Contact;

class ContactForm extends Component
{
    public $name = '';
    public $email = '';
    public $message = '';

    protected $rules = [
        'name' => 'required|min:3',
        'email' => 'required|email',
        'message' => 'required|min:10',
    ];

    public function submit()
    {
        $this->validate();

        try {
            Contact::create([
                'name' => $this->name,
                'email' => $this->email,
                'message' => $this->message,
            ]);

            // Success notification
            flash()->success('Your message has been sent!', 'Thank you');

            // Reset form
            $this->reset(['name', 'email', 'message']);

        } catch (\Exception $e) {
            // Error notification
            flash()->error('There was a problem sending your message.');
        }
    }

    public function render()
    {
        return view('livewire.contact-form');
    }
}

The Blade View

Here's the corresponding Blade view for the component:

contact-form.blade.php
<div>
    <form wire:submit.prevent="submit" class="space-y-4">
        <div>
            <label for="name" class="block text-sm font-medium text-gray-700">Name</label>
            <input type="text" id="name" wire:model="name"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
            @error('name') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>

        <div>
            <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
            <input type="email" id="email" wire:model="email"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
            @error('email') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>

        <div>
            <label for="message" class="block text-sm font-medium text-gray-700">Message</label>
            <textarea id="message" wire:model="message" rows="4"
                class="mt-1 block w-full rounded-md border-gray-300 shadow-sm"></textarea>
            @error('message') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>

        <div>
            <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent
                shadow-sm text-sm font-medium rounded-md text-white bg-purple-600 hover:bg-purple-700
                focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500">
                <div wire:loading wire:target="submit" class="mr-2">
                    <svg class="animate-spin h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                    </svg>
                </div>
                Send Message
            </button>
        </div>
    </form>
</div>

All Notification Types

You can use all the standard notification types in your Livewire components:

Success

flash()->success('Record updated successfully!')

Error

flash()->error('An error occurred while saving.')

Warning

flash()->warning('Unsaved changes will be lost.')

Info

flash()->info('Your session will expire in 5 minutes.')

Events

PHPFlasher integrates with Livewire's event system, allowing you to listen for notification events in your components. This is particularly useful for interactive notifications like SweetAlert confirmations.

SweetAlert Events

For SweetAlert, you can listen to sweetalert:confirmed, sweetalert:denied, and sweetalert:dismissed events within your component.

UserDeleteComponent.php
<?php

namespace App\Livewire;

use Livewire\Attributes\On;
use Livewire\Component;

class UserComponent extends Component
{
    public function render()
    {
        return <<<'HTML'
            <div>
                <button wire:click="deleteUser">Delete User</button>
            </div>
        HTML;
    }

    public function deleteUser()
    {
        sweetalert()
            ->showDenyButton()
            ->info('Are you sure you want to delete the user?');
    }

    #[On('sweetalert:confirmed')]
    public function onConfirmed(array $payload): void
    {
        // Delete the user here

        flash()->info('User successfully deleted.');
    }

    #[On('sweetalert:denied')]
    public function onDeny(array $payload): void
    {
        flash()->info('Deletion cancelled.');
    }
}

Event Payload

Each listener method accepts an array $payload parameter, which contains:

PayloadStructure.php
public function sweetalertConfirmed(array $payload)
{
    // Access the payload data
    $promise = $payload['promise'];
    $envelope = $payload['envelope'];

    // $promise - Contains the resolved promise data from SweetAlert
    // $envelope - Contains the notification where the event happened

    // You can use this data for further processing
    $userId = $envelope->getOption('userId'); // If you had set this option
}

Best Practice: Use Attributes for Events

With Livewire 3, use the new #[On('event')] attribute syntax for cleaner event handling. This makes your code more readable and follows modern PHP practices.

Advanced Example: CRUD Operations

Here's a more complete example showing how to implement CRUD operations with confirmations:

TasksComponent.php
<?php

namespace App\Livewire;

use App\Models\Task;
use Livewire\Attributes\On;
use Livewire\Component;

class TasksComponent extends Component
{
    public $tasks = [];
    public $taskToDelete = null;

    public $title = '';
    public $description = '';

    protected $rules = [
        'title' => 'required|min:3',
        'description' => 'required',
    ];

    public function mount()
    {
        $this->tasks = Task::latest()->get();
    }

    public function saveTask()
    {
        $this->validate();

        Task::create([
            'title' => $this->title,
            'description' => $this->description,
        ]);

        $this->reset(['title', 'description']);
        $this->tasks = Task::latest()->get();

        flash()->success('Task created successfully!');
    }

    public function confirmDelete($taskId)
    {
        $this->taskToDelete = $taskId;

        sweetalert()
            ->showDenyButton()
            ->option('confirmButtonText', 'Yes, delete it!')
            ->option('denyButtonText', 'Cancel')
            ->option('taskId', $taskId) // Store taskId in the options
            ->warning('Are you sure you want to delete this task?', 'Confirm Deletion');
    }

    #[On('sweetalert:confirmed')]
    public function deleteTask(array $payload)
    {
        $task = Task::find($this->taskToDelete);

        if ($task) {
            $task->delete();
            $this->tasks = Task::latest()->get();
            flash()->success('Task deleted successfully!');
        } else {
            flash()->error('Task not found.');
        }

        $this->taskToDelete = null;
    }

    #[On('sweetalert:denied')]
    public function cancelDelete()
    {
        $this->taskToDelete = null;
        flash()->info('Task deletion cancelled.');
    }

    public function render()
    {
        return view('livewire.tasks', [
            'tasks' => $this->tasks
        ]);
    }
}

Tips for Livewire Integration

  • Use wire:ignore on notification container elements if you're manually placing them
  • Notifications persist across Livewire updates and work with both full page refreshes and SPA navigation
  • You can pass dynamic data to your notifications using component properties
  • Store temporary state (like IDs for confirmation dialogs) in component properties

Working with Livewire SPA Mode

PHPFlasher works seamlessly with Livewire's SPA (Single Page Application) mode, ensuring notifications are displayed correctly during page transitions without reloading.

nav-link.blade.php
<a href="{{ route('dashboard') }}" wire:navigate>Dashboard</a>

<!-- In your component -->
<script>
// PHPFlasher's notifications will persist during SPA navigation
Livewire.hook('commit', ({ component }) => {
    // Any custom code that needs to run after component updates
    // PHPFlasher will automatically handle the notifications
});
</script>

Chaining Notifications with Events

You can create complex interaction flows by chaining notifications with events:

PublishArticle.php
<?php

namespace App\Livewire;

use Livewire\Attributes\On;
use Livewire\Component;

class PublishArticle extends Component
{
    public $article;

    public function confirmPublish()
    {
        sweetalert()
            ->option('title', 'Publish article?')
            ->option('icon', 'question')
            ->option('showCancelButton', true)
            ->option('confirmButtonText', 'Yes, publish it!')
            ->option('cancelButtonText', 'Not yet')
            ->question('Are you sure you want to publish this article?');
    }

    #[On('sweetalert:confirmed')]
    public function publishArticle()
    {
        // Publish the article
        $this->article->published = true;
        $this->article->save();

        // First notification
        flash()->success('Article published successfully!');

        // Second notification (after a delay)
        sweetalert()
            ->timer(3000)
            ->option('showCancelButton', true)
            ->option('confirmButtonText', 'Yes, share it!')
            ->option('cancelButtonText', 'No thanks')
            ->option('actionType', 'share') // Custom option to identify action
            ->question('Do you want to share this article?');
    }

    #[On('sweetalert:confirmed')]
    public function handleConfirmation(array $payload)
    {
        $envelope = $payload['envelope'];
        $actionType = $envelope->getOption('actionType');

        if ($actionType === 'share') {
            // Show sharing UI
            $this->dispatch('show-share-modal', articleId: $this->article->id);
        }
    }

    public function render()
    {
        return view('livewire.publish-article');
    }
}

Additional Integrations

PHPFlasher works with other popular Livewire plugins and Laravel features.

Alpine.js Integration

PHPFlasher works perfectly with Alpine.js directives in your Livewire components.

<div x-data="{ show: false }">
    <button x-on:click="show = true; $wire.showToast()">
        Show Toast
    </button>
</div>

Laravel Blade Integration

Mix Blade directives with Livewire and PHPFlasher notifications.

@if (session('status'))
    <script>
        document.addEventListener('livewire:initialized', () => {
            flasher.success('{{ session('status') }}');
        });
    </script>
@endif

Ready to enhance your Livewire UI?

Start using PHPFlasher today and give your users beautiful notifications in minutes!