Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

onurzdgn's avatar

JS Code Review

Hello everyone. I am using Laravel 11 and Livewire 3. I am trying to use js in livewire blade file. I did this:

@if ($errors->any())
    @foreach ($errors->all() as $error)
        @script
            <script>
                toastr.warning("{{ $error }}", "Hata!");
            </script>
        @endscript
    @endforeach
@endif

@if (session('message'))
    @script
        <script>
            console.log("sa");
        </script>
    @endscript
@endif

How can I improve this?

0 likes
5 replies
RemiM's avatar

Your goal is to have a form action or something similar that triggers notifications?

On a side note, I believe Toastr is no longer actively maintained and relies on JQuery as a dependency, so you might want to explore alternatives that are more future-proof.

onurzdgn's avatar

@RemiM Yes, you understood my goal correctly. The toastr theme I use belongs to, but I will investigate your alternative offer. Do you have any suggestions as an alternative?

RemiM's avatar

@onurzdgn For the suggestions, you can have a look here. Of course, make sure the library you pick works with Alpine and Livewire. As long as it's using vanilla JS, you should be good to go.

As for your main concern, you can leverage Livewire Events to achieve what you're looking for.

In summary, within your component, you would define your save() method and use the dispatch function to trigger the desired event:

The Livewire component:

The Blade file:

<div x-data>
    <form wire:submit="save">
        <div>
            <label for="title">Title</label>
            <input type="text" id="title" wire:model="title">
            @error('title') <span>{{ $message }}</span> @enderror
        </div>
        
        <div>
            <label for="content">Content</label>
            <textarea id="content" wire:model="content"></textarea>
            @error('content') <span>{{ $message }}</span> @enderror
        </div>
        
        <button type="submit">Create Post</button>
    </form>

    <!-- Notification Listener -->
    <div x-on:post-created.window="toastr.success($event.detail.message)"
         x-on:post-error.window="toastr.error($event.detail.message)">
    </div>
</div>

Snapey's avatar

its generally not a good idea to use livewire to add and remove javascript components from the page and expect them to be reactive.

Please or to participate in this conversation.