I’m testing out Livewire with a Laravel shopping cart plugin. To add items to the cart you call a function, passing in id, name, quantity, price, and an optional array of metadata:
<button wire:click.prevent="addToCart('{{ $id }}', '{{ $product_name}}', 1, {{ $price }}, ['size' => '{{ $size }}'])">Add to Cart</button>
The rendered HTML looks perfect, but when I click the button I get:
Uncaught SyntaxError: invalid arrow-function arguments (parentheses around the arrow-function may help)
It doesn’t seem to like the => in the array assignment. Does anyone know a fix?
Advertisement
Answer
there is no such thing as an associative array in javascript, it’s an object and as such you need to provide a valid object (if you still want it with the same structure).
<button wire:click.prevent="addToCart('{{ $id }}', '{{ $product_name}}', 1, {{ $price }}, {{json_encode(['size' => $size ])}})">Add to Cart</button>
or
@json(['size' => $size ]) //instead of {{json_encode(['size' => $size ])}}