Laravel Livewire couldn't listen to specific event - Stack Overflow

admin2025-03-13  0

I wrote a very simple event in Laravel, and I want to listen to this event in my Livewire components. The event works perfectly on the front-end, and I have no issues listening to it there. However, no matter how much I try, I can't get it to work in Livewire.

Event Definition:

class NewProductAddedToCart implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public string $idString;

    public function __construct(string $idString)
    {
        $this->idString = $idString;
    }

    public function broadcastOn(): Channel|array
    {
        return new Channel('new_cart_added');
    }

    public function broadcastAs(): string
    {
        return 'add';
    }

    public function broadcastWith(): array
    {
        return [
            'idString' => $this->idString,
        ];
    }
}

Triggering the Event (used inside Laravel commands):

event(new NewProductAddedToCart($idString));

Front-end Listener (Works Correctly):

<script type="module">
    window.Echo.channel('new_cart_added').listen('.add', (e) => {
        console.log('new_cart_added: TRIGGERED!!', e.idString);
        $('body').find('.jGrowl').attr('class', '').attr('id', '').hide();
        $.jGrowl('A new product has been added to the cart', {
            position: 'top-left',
            theme: 'bg-teal text-white YekanBakhBold'
        });
    });
</script>

Livewire Listener (Not Working at All):

class ContentComponent extends Component
{
    #[On('echo:new_cart_added,.add')]
    public function new_cart_added()
    {
        Log::info('SALAM');
    }
}

No matter what I do, the Livewire listener does not trigger.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1741854719a184021.html

最新回复(0)