dispatchBrowserEvent on mount

Hi.
I am using the multiple toaster notifications from this guide: https://laravel-livewire.com/screencasts/s8-toasters and they work great!
What I am looking to do is show a notification after saving and redirecting.
It could be like this

public function save()
{
    $this->validate();
    $this->post->save();
    session()->flash('notify', 'Post successfully updated.');
    return redirect()->to('/posts');
}

Then I am assuming that on users.php in mount I would do this:

if (request()->session()->has('notify')) {
    $message = request()->session()->has('notify');
    $this->dispatchBrowserEvent('notify', ['type' => 'success', 'text' => '$message']);
}

But it does nothing.

Any ideas on how I could show a notification after saving & redirecting?

Hey, @vayurobins

You don’t need to dispatch any events, it simply after flashing the session and redirecting to the posts route in your posts.blade.php or in custom alert blade included inside your posts blade file you should do the following:

@if(session()->has('notify'))
  <div> {{ session()->get('notify') }}
@endif

And after that you are ready to go.

Thanks @skywalker! I don’t think that is correct though. I need to somehow tricker the livewire notification component to display. This is what I don’t know how to do.

You need the notification appears before or after saving data?

Well, when the user clicks the save button, the page redirects away from the edit page to the post list page. So it is after, on the post list page.

Alright, do what’s above. Cause that’s what I’m doing in my whole livewire projects and it works very well.

Let’s assume you are about creating an article.

In create.blade.php

<form ..>
<button wire:click="save"></dutton>
</form>

In Create.php component

...
public functoin save()
{
     Article::create($data);
   session()->flash('success', 'Your article was created successfully');
   return redirect()->to('/articles');
}
...

In index.blade.php

@if(session()->has('success'))
  <div>
    {{ session()->get('success') }}
  </div>
@endif

Thanks for helping @skywalker, but I don’t see how this can trigger the notification component. Have you seen the video and the code here? https://laravel-livewire.com/screencasts/s8-toasters
What you are suggesting is simply posting the session in a plain div. I have a notification toaster component that Caleb built with LIvewire and AlpineJS, which is triggered with dispatchBrowserEvent.

I don’t see the videos because it’s restricted to GitHub sponsors only and I’m not :frowning:

But I do it with sweet alert by triggering the JavaScript code if there is a session called.

P.S: @Snapey wrote about this here, you can take a look.

Thanks, yeah I don’t know. I am using the dispatchBrowserEvent continuously through my application, however, it will not work on mount/page-load, this is where I am stuck.

If you are doing a redirect then the issue is not with Livewire. Just flash the message and use the regular Laravel methods for detecting flash messages and display them.

The Livewire tutorial you mention is for same-page notification

To display notifications with better view, you can use Sweet alert.

For example: you can make a custom notifications view resources/notifications/alert.blade.php by doing the following:

Install Sweet alert

npm install sweetalert2

Import Sweet alert in bootstrap.js

import Swal from 'sweetalert2';

window.Swal = Swal

in alert.blade.php

@if(session()->has('success'))
    <script>
        Swal.fire({
            position: 'top-center',
            icon: 'success',
            title: '{{session()->get('success')}}',
            showConfirmButton: false,
            timer: 2000
        })
    </script>
@endif
@php
    session()->forget('success')
@endphp

@if(session()->has('error'))
    <script>
        Swal.fire({
            position: 'top-end',
            icon: 'error',
            title: '{{session()->get('error')}}',
            showConfirmButton: false,
            timer: 2000
        })
    </script>
@endif

and in your base view (e.g base.blade.php) include the alert view

@include('notifications.alert')

Then, you can make the redirections with sessions easily.

Hope that help :slight_smile:

@Snapey why would you say that it is a same-page notification? What makes it that? Is it because it is not possible to dispatch browser events in mount? I would like to understand why it’s not working.
Is it no possible to dispatch events at page load? I don’t think it shoul only be possible to di this on click events or mouseevents?

Thanks a lot @skywalker I appreciate your help. :slight_smile: Before I start using third party libraries, I would like to try and understand why it’s not working and to see if there is a way to dispatch an event on page load, that will trigger the notification.

The technique illustrated on the Surge project is to show a status update on the same page. You did not leave the page, you only indicated to the html content that a message should be shown briefly.

If your Livewire update results in a redirect to a new route, then that new route and page view needs to get the status message so that it can show it over the top of its normal content. This is normally performed by a flash to the session, and some code in your view that checks for the presence of a flashed message and shows it to the view.

This is something you handle in blade and NOT a Livewire concern.

For instance, in your layout template, you would add code like

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

and then the data you flashed to session before the redirect would be displayed on the page,

This is not something you need to handle in the livewire mount method.

Sorry, I don’t see why the technique illustrated on the Surge project is to show a status update on the same page only. I kinda disagree with that and I still kinda like to know why the notification cannot be called anywhere, like on mount or updating.

When mounting a page or updating a page, then we are still on a “same page” situation. If you forget about the redirect, but just want to display the notification right after the page has loaded, then I would think I could trigger it in the mount method?

I don’t know what else to say. Just learn the basics of Laravel I guess…

@Snapey is right @vayurobins.
TBH I don’t watch the premium screencasts that Caleb has released because I’m not a subscriber, but if you want to trigger a notification in the same page this is the way and if you want to trigger a notification outside the same page use the other way.

Okay no problem, but I don’t think this is basic Laravel. The toaster notification in Surge is not basic Laravel as far as I know. So is it not possible to load the toaster in the Surge project on page load? Like a “Hello and welcome” notification, when one enters the page? Disregarding redirects and sessions (<-- this is basic Laravel, and I do understand this :wink: ).

The toaster notification in Surge is fired when the component sends a browser event

You cannot send events from the mount method. Think of it like the constructor. If you want something to appear in the view you must make it a public property, pass it directly to the rendered view or put it in session and pull it from there.

None of these are FLASH. Flash is putting a value in session for the next request cycle.

1 Like

@skywalker first reply is correct

The important bit is that you are redirecting. Despatching a browser event only goes to the javascript on the page that you are LEAVING. It may well act on your dispatched event, but you will never see it because the browser reloads the page.