'How in Laravel run JavaScript code stored in php variable?

In the livewire component, I have the script tag:

<script>
{!! $script !!}
</script>

Let's say the $script variable contains console.log('test');

It is executed once - no surprise documentation explains this. The recommendation is to emit a custom event and listen to it, but the problem is that it does not work with code in a variable. In other words, this works:

<script>
    document.addEventListener('custom-event', () => {
        console.log('test');
    })
</script>

but this does not:

<script>
    document.addEventListener('custom-event', () => {
        {!! $script !!}
    })
</script>

Any idea how to solve this?



Solution 1:[1]

try this

in component

public $foo;

$this->dispatchBrowserEvent('custom-event', ['foo' => $this->foo]);

in view

<script>
    window.addEventListener('custom-event', event => {
          alert('here value foo: ' + event.detail.foo);
          console.log(event.detail.foo);
    })
</script>

Solution 2:[2]

Try this ->

<script>
    document.addEventListener('custom-event', () => {
        {!! json_encode($script) !!}
    })
</script>

I hope it was helpfull! :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdulmajeed
Solution 2 EvilDeadTX