Emitting events with data [Solved]

What seems to be the problem:
What is the proper way to send blade variables to a Livewire controllers via an event?

Steps to Reproduce:

Here’s what I have:

@foreach ($adGroups as $group)
    <a href="#" wire:click="$emit('updateShowGroup', $group)" class="block px-6 py-4 font-semibold bg-white border-b ">
        <div>{{ $group }}</div>
    </a>
@endforeach

I get $group is undefined in the console. I’m not seeing anything in the docs about passing along blade variables, just plain strings. Using {{ $group }} seems to give me odd results.

Thanks for any help! I’m just getting started with Livewire and loving it vs. a large JS framework.

Are you using the latest version of Livewire:
Yes

Do you have any screenshots or code examples:

Hey!

have you declared and defined a public variable (group) in your component?

$group is just locally defined within the @foreach loop

The issue here is that you are trying to reference a PHP variable in a JS expression. What is the value of $group?

Right now it’s just a string. I’m sure I’m making this harder than it needs to be.

{{ $group }} is needed to turn the PHP object into somethign JS can use (other wise the string ‘$group’ is used).

Maybe {{ dd($group) }} will help work out what $group actually is. I assume its something like an id?

If $group is a string, here’s the fix:
@foreach ($adGroups as $group)

{{ $group }}


@endforeach

(notice the single quotes and blade echo I added around $group)

I know it’s a little confusing, but if you carefully look, you should see that “$emit…” is a plain string that JavaScript interprets. You need to echo out the php variable into the JavaScript string.

Hope that makes sense.

Thanks!

1 Like

Finally got back to this, and after changing to single quotes it worked! Thanks @calebporzio!

1 Like