Here's an example code snippet in Laravel that demonstrates triggering a Livewire notification component when a Laravel event is fired:
In your Livewire component:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class NotificationComponent extends Component
{
protected $listeners = ['notificationReceived' => 'showNotification'];
public $notificationMessage;
public function showNotification($message)
{
$this->notificationMessage = $message;
$this->dispatchBrowserEvent('show-notification');
}
public function render()
{
return view('livewire.notification-component');
}
}
In your view file for the Livewire component:
<div>
@if($notificationMessage)
<div x-data="{show: true}" x-show.transition.duration.1000ms="show" x-init="setTimeout(() => show = false, 5000)" class="bg-green-500 text-white p-4 rounded-md mb-4">
{{ $notificationMessage }}
</div>
@endif
</div>
In your Laravel event listener:
<?php
namespace App\Listeners;
use App\Events\NotificationReceived;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class SendNotification implements ShouldQueue
{
use InteractsWithQueue;
public function handle(NotificationReceived $event)
{
$message = $event->message;
// Trigger Livewire component to show notification
event('notificationReceived', $message);
}
}
This assumes that you have already set up your Livewire component and registered your Laravel event listener. Also, this example assumes you are using Laravel 8 with Livewire v2.0+. If you're using an older version of Livewire, the syntax may differ slightly.