Emit a livewire event from normal laravel controller

I made a livewire toaster component and that fires up and listen to emitted envet like:

$this->emit('showAlert', ['type' => 'success', 'title' => 'This is the title', 'message' => 'This is the message']);

What i want to know is if there is a way to emit an event from a regular laravel controller that can be listened from a livewire compoment.

Currently built in? No. Completely possible? Yes. You just have to get a little creative with sessions. For your case, I can do you one better because I’ve already done exactly this, and you bypass the actual emitting part. I’m just going to copy and paste some code here that you can adapt to how you need it.

Trait for your controller (or whatever else) to use:

trait SendsAlerts
{
    public function sendAlert(string $type, string $message): void
    {
        session()->push('alerts', ['type' => $type, 'message' => $message]);
    }
}

Mount method of my livewire AlertSystem component:

public function mount(): void
{
    if (session()->has('alerts')) {
        foreach (session('alerts') as $alert) {
            $this->receiveAlert($alert['type'], $alert['message']);
        }
        session()->forget('alerts');
    }
}

All you should have to do is add in the param for the title and change receiveAlert to whatever method name you use. You can use the session flash instead of manually using put() and forget(), and also class it out if you don’t like traits.

1 Like

Thank you very much!

Why would a controller be running?

Are you thinking about events created by other users? In which case, use Laravel echo to broadcast the event.

Just in case of i do not refactor all the app to livewire components, so for example, when some data is save on database, throws the evento to show toaster.

I know that when livewiring we do not need controller, but, its just i dont wanto to refactor all…