Yousarssif's avatar

Emit to parent element on livewire.

I want to update the parent element when I child got updated. assuming I have this livewire like component function which sets or create likes.

public function postLiked($id)
    {
        if (! $this->liked) {
            Like::create([
                'user_id' => auth()->user()->id,
                'post_id' => $id,
            ]);
            $this->liked = true;
        } else {
            Like::where(['post_id' => $id, 'user_id' => auth()->user()->id])->delete();
            $this->liked = false;
        }
    }

I want the parent element to be updated whenever the child is updated.

0 likes
5 replies
LaryAI's avatar
Level 58

To emit an event to the parent component in Livewire, you can use the emitUp() method. In this case, you can emit an event from the child component and listen for it in the parent component to update the parent element.

Here's an example of how you can emit an event from the child component:

public function postLiked($id)
{
    // your code to create or delete a like

    $this->emitUp('likeUpdated');
}

In this example, we're emitting an event called likeUpdated to the parent component using the emitUp() method.

Now, in the parent component, you can listen for this event and update the parent element. Here's an example of how you can do that:

// in the parent component

protected $listeners = ['likeUpdated'];

public function likeUpdated()
{
    // update the parent element
}

In this example, we're listening for the likeUpdated event using the $listeners property. When the event is emitted from the child component, the likeUpdated() method in the parent component will be called, and you can update the parent element there.

Yousarssif's avatar

@LaryAI still confused. how can I update the parent knowing that it is a laravel component not a livewire one.

newbie360's avatar

@Yousarhk Because each Livewire component has a signature, when you view the page source code, you can see a very long string something like this, in this long string contain alot informations, such like listeners name

<div wire:id=".......hash-id.........." wire:initial-data="{&quot;fingerprint

depends on your use case, just simple add a listener in the parent component

protected $listeners = ['exampleRefresh' => '$refresh'];

and in the child component fire

$this->emitUp('exampleRefresh');

in the above example, used $refresh to re-render the component, of course you can set the $listeners point to any method

Yousarssif's avatar
Yousarssif
OP
Best Answer
Level 2

@newbie360 thank you it is fixed now. the problem was that I had wire:ignore on the parent element which prevent other childs from being updated.

lgmm's avatar

You can listen in blade in the parent and stop propagation eg:

@saved.stop="handleSaved($event.detail.fieldName, $event.detail.fieldData)"

Please or to participate in this conversation.