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

lukeboy_2002's avatar

Likes from larval to livewire with broadcast

Hi I want to have a polymorphic relationship for likes. Now it is only for tweets. sometime ago I made a polymorphic relationship for likes. Now I want to use this in livewire component and after updating the likes I want to broadcast it. I don't know how exactly I must do it. How to convert my controller to a livewire component and how to add the broadcasting.

This is my controller:

I also have an Event for Broadcast.

0 likes
1 reply
LaryAI's avatar
Level 58

To convert your existing controller logic into a Livewire component and add broadcasting, you'll need to follow these steps:

  1. Create a Livewire Component: First, create a Livewire component that will handle the likes functionality.

  2. Move Logic to Livewire Component: Transfer the logic from your controller to the Livewire component.

  3. Broadcast the Event: Use the existing event to broadcast changes when a like is added or removed.

Here's how you can achieve this:

Step 1: Create a Livewire Component

Run the following command to create a Livewire component:

php artisan make:livewire LikeComponent

Step 2: Implement the Logic in the Livewire Component

Edit the LikeComponent.php file to include the logic for liking and unliking, and dispatch the event for broadcasting.

Step 3: Create the Blade View

Create a Blade view for the Livewire component at resources/views/livewire/like-component.blade.php:

<div>
    <button wire:click="like">Like</button>
    <button wire:click="unlike">Unlike</button>
    <span>{{ $likesCount }} likes</span>
</div>

Step 4: Update Your Event

Ensure your TweetLikesUpdated event is set up to broadcast on the correct channel. You might need to adjust the channel name based on your application logic.

Step 5: Use the Component in Your Blade Template

Include the Livewire component in your Blade template where you want the like functionality to appear:

<livewire:like-component :type="$type" :id="$id" />

Step 6: Set Up Broadcasting

Ensure your broadcasting is configured correctly in config/broadcasting.php and that you have a broadcasting service like Pusher or Laravel Echo set up to listen for the events.

This setup should allow you to manage likes using Livewire and broadcast updates in real-time. Make sure to test thoroughly and adjust the channel names and event data as needed for your specific application.

Please or to participate in this conversation.