Best way to make toaster notification with javascript

Any one with idea how implement this, if someone create a comment or reply a comment or create a post will notify via toaster notification like sweetalert or toastr

2 Likes



I have made a Toast like component. It is a combination of Livewire and Alpine JS. It is included in app.blade.php.

The blade component is like

<div class=" fixed bottom-0 inset-x-0 mb-6 mx-6 px-6 py-5 max-w-sm rounded-lg pointer-events-auto {{ $alertTypeClasses[$alertType] }}"
x-data="{show:false}"

@toast-message-show.window=“show = true; setTimeout(() => show=false, 5000);”

x-show=“show”
x-cloak
>

{{ $message }}
</div>

It will show the component at bottom right corner, you can surely adjust as you like and restyle it. The main point is that it listens for a browser event

@toast-message-show.window=“show = true; setTimeout(() => show=false, 5000);”

and shows it for 5 secs and again closes it. I am sure you can make suitable style changes (I suck in that).

The component is simple:

protected $listeners = ['show-toast' => 'setToast'];
public $alertTypeClasses = [
    'success' => ' bg-green-500 text-white',
    'warning' => ' bg-orange-500 text-white', 
    'danger' => ' bg-red-500 text-white', 
];

public $message = 'Notification Message';
public $alertType = 'success';

public function setToast ($message, $alertType)
{
    $this->message = $message;
    $this->alertType = $alertType;
    

    $this->dispatchBrowserEvent('toast-message-show');
}

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

Essentially it listens for the event “show-toast” and sets data from the event and finally gives a browser event “toast-message-show”.

Now, from any Livewire component, you can do

$this->emit(‘show-toast’, ‘New Post has been successfully created!’, ‘success’);

3 Likes

Nice one! Why is this method not documented? Was looking for this, thanks! :smiley:

when i try the emit like bellow

$user->forceFill([
                'name' => $input['name'],
                'email' => $input['email'],
                ])->save();
                $this->emit('show-toast', 'Saved!', 'success');

i got an error like bellow:
Error Call to undefined method App\Actions\Fortify\UpdateUserProfileInformation::emit()
can someone give solution?

Thanks

Emit is a method in the livewire class, looks like you are trying to call it from inside of the update action class.

yes, i try to called it from inside update profile action.
is there a way to make it work when i press the saved button?

The short answer is to call emit in the method that is triggered from your wire:click/wire:submit on your component.

i still confuse, can you show some example with a code?