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

Scop's avatar
Level 1

How to i notify one livewire component to another component ?

First sorry for my english...

my problem is

i have two components, one component (items.php) this component use for add to cart. my second component is navbar.php, there is a cart symbol with number

the user when click add to cart, in that same time number of carts number want to increase...

for now i can do that things well... everything is fine. but real time number (cart number) not updating.

0 likes
18 replies
Scop's avatar
Level 1

his is my item.php

public function requestToApprove() { $catchNotify = ItemRequestNotification::create([ 'user_email' => Auth::user()->user_email, 'user_name' => Auth::user()->user_name, 'pending_items' => $numberOfRequestedItems, 'notification_message' => 'New Items pending for Approvals', 'notification_type' => 'Pending for Approvals Notification', ]); return session()->flash('approvalRequest', 'Inventory List Successfully Sended for Approval'); } }

navbar.php

public function render() { return view('livewire.navbar',[ 'notMarkedNotifications' => DB::table('item_request_notifications')->where('notification_status', 'not marked')->count(),]);}

at the same time the notification number and notification want to load

I can explain this function via one scenario...

in facebook, when someone send friend request or like the our post at the same time we got real time notification

this same function I need

ajaypatel9016's avatar

I hope this helps:

In Livewire, to communicate between two components in real-time (like updating the cart count in the navbar when an item is added), you can use events. Here’s how you can do it:

Step 1: Emit an Event from the items.php Component

When the user clicks "Add to Cart" in the items.php component, you can emit an event that will notify the other component (navbar.php) to update its cart count.

In your items.php component:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Items extends Component
{
    public function addToCart($itemId)
    {
        // Your add to cart logic here

        // Emit an event to update the cart count
        $this->emit('cartUpdated');
    }

    public function render()
    {
        return view('livewire.items');
    }
}

Step 2: Listen for the Event in the navbar.php Component

In the navbar.php component, listen for the cartUpdated event and update the cart count when it’s received.

In your navbar.php component:

Step 3: Use Alpine.js for Immediate UI Feedback (Optional)

If you want the cart count to update immediately without a page refresh, you can use Alpine.js for quick visual feedback. For example:

<div x-data="{ cartCount: @entangle('cartCount') }">
    <span x-text="cartCount"></span>
</div>

Explanation

  • Emit event: items.php emits cartUpdated when an item is added to the cart.
  • Listen for event: navbar.php listens for cartUpdated and calls updateCartCount to refresh the cart number.

Now, when an item is added to the cart, the cartUpdated event will notify the navbar.php component to update the cart count in real-time.

1 like
Phread's avatar

@Scop Livewire v3 replaced emit with dispatch. emit will error out....

1 like
MouteeSabouni's avatar

Hey, @scop. I have done a project that has something very similar to what you're asking about.

You may check it here:

https://github.com/MouteeSabouni/shop-sphere

And as a response to you, there are many ways to handle this, but the simplest is you can use $this->dispatch('cart-updated') in the method where you want the logic of firing an event happens. Then you may use On attribute above a method by which you listen to that event and, say, change $cartUpdated value from false to true.

That way, you can simply let your notification element visibility be controller by the state of that $cartUpdated variable using x-show="cartUpdated" on the HTML tag.

1 like
Scop's avatar
Level 1

@MouteeSabouni hi thanks for your reply

i already try this items.php

$this->dispatch('cart-updated')

and, navbar.php

#[On('cart-updated')] protected $listeners = [ 'cart-updated' => '$refresh', ];

but this is not work, i open two browser tabs in same window, when i send request, its didnt update at the same time. after page refresh i got the notification.

i dont know, i think i miss something please can you explain your idea step by step? based on my code? (i didnt understand that html tag)

thank you

MouteeSabouni's avatar

@Scop Sure.

So, you dispatch the event cart-updated. Now you want to listen to it to refresh the component or show a notification. You can go to your navbar.php and create a method like this

#[On('cart-updated')]
public function showNotification(): void
{
	$showNotification = true; // Of course you need to define this variable up.
}

Now, on the HTML element that has the notification, say a div, you add this.

<div id="notification" x-show="showNotification" x-cloak>
	<!-- The notification -->
</div>

The x-show in Alpine will only show that div (notifcation) if the condition is true, which is in this case, a variable that we are setting to true in the method above. And x-cloak is used to hide the element when first opening the page. It's just something that happens for some reason. When you open the page, you will see the notification in a blink, and it will disappear within milliseconds. So, adding x-cloak will hide it by default unless what's in x-show equals true.

I hope this helps.

1 like
Hector-moya's avatar

Hi @scop, have you checked if your dispatched event is hitting your navbar component?

To make sure your navbar component is listening to your item.php dispatch event, you could create a updateCartCount method to call upon dispatching cart-update event, for instance:

item.php

public function requestToApprove() { // ...Your code

$this->dispatch('cart-updated') }

navbar.php

$listeners = ['cart-updated' => 'updateCartCount'];

public function updateCartCount() { dd('Your dispatch is working'); }

if you don't see the message, it means your navbar component is either not a parent-child or sibling component of item.php. If that's the case, then you need to create a global listener. The livewire doc goes into detail on how to do that:

https://livewire.laravel.com/docs/events#listening-for-livewire-events-from-global-javascript

1 like
Scop's avatar
Level 1

hi @Hector-moya, Thank you reply me.

i already try this before, not working :(

when I using wire:poll, its working. bt wire:poll not suitable for me because its affect my other js things.. so I need another different alternatives. (when item.php method run completely, navbar.php's method want to refresh or update instantly)

Hector-moya's avatar

Can you show us the components to see how they interact?

1 like
Scop's avatar
Level 1

@Hector-moya sure..! (sorry for my poor english)

this is my items.php (livewire)

public function requestToApprove() {

    $checktheApprovalrequestTbl = DB::table('temp__items')->count();
    $numberOfRequestedItems = DB::table('temp__items')->where('ask_to_approval','hold')->count();
    $requstedAllItems = DB::table('temp__items')->where('ask_to_approval','hold')->get();
    $requstedUserName = Auth::user()->user_name;
    $AllSuperAdmins = DB::table('sysusers')->where('user_role','Super Admin')->get();
    $requestUserRole = Auth::user()->user_role;


    if ($checktheApprovalrequestTbl === 0) {
        return session()->flash('approvalRequestError', 'Error: The operation cannot proceed because the table is empty.');
    } else if ($numberOfRequestedItems != 0) {

        DB::table('temp__items')->update(['ask_to_approval' => 'pending']);

       foreach($AllSuperAdmins as $admin)
       {
        Mail::to($admin->user_email)->send(new requestToApproveItem($requestUserRole,$numberOfRequestedItems,$requstedUserName,$requstedAllItems));
       }

      $catchNotify = ItemRequestNotification::create([
        'user_email' => Auth::user()->user_email,
        'user_name' => Auth::user()->user_name,
        'pending_items' => $numberOfRequestedItems,
        'notification_message' => 'New Items pending for Approvals',
        'notification_type' => 'Pending for Approvals Notification',
       ]);



        return session()->flash('approvalRequest', 'Inventory List Successfully Sended for Approval');
    }

    else{return session()->flash('approvalRequestError', 'Error: No items available for approval request at this time.');}
}

this method for add items to temporary item save function, at the same time i save the records for ( $catchNotify ) notifications.

this is my navbar.php for fetching notifications

public function PendingItemsNotify() { $this->notMarkedNotifications = DB::table('item_request_notifications')->where('notification_status', 'not marked')->count(); }

public function render() {

    $this->PendingItemsNotify();
    return view('livewire.navbar',[

    'allpendingNotificationList' => DB::table('item_request_notifications')->where('notification_status', 'not marked')->orderBy('created_at' , 'desc')->get(),

    ]);


}

this is for fetching notification value and notification datas

this is my navbar.blade.php

                    @foreach ($allpendingNotificationList as $notification)
                    <div wire:ignore class="app-notifications" wire:click='notificationMarked({{ $notification->id }})'>
                        <span class="app-notification-heading">{{ $notification->notification_type }}</span>
                        <span>{{ $notification->pending_items }} Items requested for approvals</span>
                        <span>{{ $notification->user_email }} &nbsp;
                            {{ $notification->user_name }}</span>
                        <span class="app-notification-time">
                            @php
                            $notificationTime = $notification->created_at;
                            $notificationTime = \Carbon\Carbon::parse($notification->created_at);
                            $timeDiff = $notificationTime->diffForHumans();
                            @endphp
                            {{ $timeDiff }}
                        </span>
                    </div>
                    @endforeach
                    <div class="app-notification-panel-footer">
                        <span wire:click='notificationAllMarked'>Notification marked as read </span> &nbsp;<a
                            class="app-refresh-link" wire:click='$refresh'>Refresh</a>
                    </div>
                    @else
                    <div class="app-notifications">
                        <span class="app-notification-heading"> No notifications available. &nbsp;<a
                                class="app-refresh-link" wire:click='$refresh'>Refresh</a></span>
                    </div>
                    @endif
                </div>
            </div>

this is my whole code

thank you

asheek_mohammed's avatar

You should include the navbar.php inside the items.php. and then you can use dispatchTo from items component to communicate with navbar.

asheek_mohammed's avatar

@Scop

<button wire:click="$dispatchTo('cart','add-cart')"
 class="text-primary">Add to cart</button>	

<livewire:cart />

the code above is inside items.php.

then on navbar.php

#[On('add-cart')]
    public function addToCart() //you can add any function name
    {
        $this->cartItem ++ ;
    }

this way it will connect from items to cart

Scop's avatar
Level 1

@asheek_mohammed

but i have different type of function

public function PendingItemsNotify() { $this->notMarkedNotifications = DB::table('item_request_notifications')->where('notification_status', 'not marked')->count(); }

Please or to participate in this conversation.