A solid integration with Laravel Livewire

Last updated at 08 May 2022 | Published at 29 August 2021

If you like PHPFlasher please consider giving it a on github or by spreading the word on twitter. Your support allows me to keep this package up-to-date and maintainable. Thank you


PHPFlasher offers a solid integration with Livewire v2.

Requirements

PHP >= 7.2 Laravel >= 7.0


Installation

Please follow the same installation steps as for the Laravel Installation package.


Usage

Dispatch notifications from your components

namespace App\Http\Livewire;

use Livewire\Component;

class MyComponent extends Component
{
    public function someAction()
    {
        toastr()->addSuccess('notification using toastr library'); // composer require php-flasher/flasher-toastr-laravel
        sweetalert()->addInfo('notification using sweetalert library'); // composer require php-flasher/flasher-sweetalert-laravel
    }

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

Events

For sweetalert you can listen to Confirmed, Denied and Dismissed from withing you component

namespace App\Http\Livewire;

use Livewire\Component;

class MyComponent extends Component
{
    protected $listeners = [
        'sweetalertEvent', // for all events from sweetalert
        'sweetalertConfirmed', // only when confirm button is clicked
        'sweetalertDenied' => 'onDeny', // if you want a custom method name
        'sweetalertDismissed',
    ];

    public function someAction()
    {
        sweetalert()->showDenyButton()->addInfo('confirm or deny action');
    }

    public function sweetAlertEvent(array $payload)
    {
        toastr()->closeButton()->addInfo('Event received from sweetalert');
    }

    public function sweetAlertConfirmed(array $payload)
    {
        toastr()->addSuccess('The "Confirm" button was clicked');
    }

    public function onDeny(array $payload)
    {
        toastr()->addError('The "Deny" button was clicked');
    }

    public function sweetAlertDismissed(array $payload)
    {
        toastr()->addWarning('The "Cancel" button was clicked');
    }

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

If the name of the event and the method you’re calling match, you can leave out the key. For example: protected $listeners = ['sweetalertConfirmed']; will call the sweetalertConfirmed method when the sweetalertConfirmed event is emitted.

event handlers context

Every listener method accept an array $data parameter which contain the following data :

public function sweetAlertConfirmed(array $payload)
{
    $promise = $payload['promise'];
    $envelope = $payload['envelope'];
}

promise : the resolved promise from sweetalert.

envelope : the notification where the event happened.

Younes

PHPFlasher is a project by Younes KHOUBZA.