DEV Community

Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on

Livewire Alert

Let's create a simple Livewire Alert component, to replace a normal conventional alert message.

Assuming you are using Laravel Jetstream as well.

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Alert extends Component
{
    public $displayingModal = false;

    public $state = [
        'title' => '',
        'message' => '',
    ];

    protected $listeners = [
        'displayAlert' => 'display',
    ];

    public function display($title, $message)
    {
        $this->state['title'] = $title;
        $this->state['message'] = $message;

        $this->displayingModal = true;
    }

    public function render()
    {
        return view('livewire.alert');
    }
}
Enter fullscreen mode Exit fullscreen mode

The blade file:

<div>
    <x-jet-dialog-modal wire:model="displayingModal">
        <x-slot name="title">
            {{ $state['title'] }}
        </x-slot>

        <x-slot name="content">
            <p>
                {{ $state['message'] }}
            </p>
        </x-slot>

        <x-slot name="footer">
            <x-jet-button class="ml-3" wire:click="$set('displayingModal', false)" wire:loading.attr="disabled">
                {{ __('Close') }}
            </x-jet-button>
        </x-slot>
    </x-jet-dialog-modal>
</div>
Enter fullscreen mode Exit fullscreen mode

Once you have the component configured, you may use and trigger by using emitTo:

$this->emitTo('alert', 'displayAlert',  'Greeting', 'Hello World!');
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)