skip to Main Content

On laravel 10 site using docs at https://dev.to/koossaayy/laravel-livewire-multiple-selection-with-virtual-select-1f87
I try to make multiselection,
but copypasting code of the project I got "Uncaught SyntaxError: Unexpected token ‘:’ "error on blade code :

<div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/virtual-select.min.js" integrity="sha256-Gsn2XyJGdUeHy0r4gaP1mJy1JkLiIWY6g6hJhV5UrIw=" crossorigin="anonymous"></script>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/virtual-select.min.css" integrity="sha256-KqTuc/vUgQsb5EMyyxWf62qYinMUXDpWELyNx+cCUr0=" crossorigin="anonymous">

    resources/views/livewire/admin/users-permissions-editor.blade.php

    <div>

        <div id="permissions"></div>

            <script>
                const permissions = [
                    @foreach ($permissions as $permission)
                    {
                        label : '{{ $permission->name }}' , // ERROR POINTING THIS LINE
                        value : '{{ $permission->id }}'
                    },
                    @endforeach
                ];
                VirtualSelect.init({
                    ele: '#permissions',
                    multiple: true,
                    options: permissions,
                });
            </script>

    </div>
</div>

I replaced all symbols in code ‘{{ $permission->name }}’ and tried to wrap keys with " symbol :

@foreach ($permissions as $permission)
{
    "label" : '{{ $permission->name }}' ,
    "value" : '{{ $permission->id }}'
},
@endforeach

I which way have I to pass an array here ?

ADDITIVE INFO :

I remade my script as :

<div>

    <div id="permissions"></div>

    @script
    <script>
        const permissions = [
                @foreach ($permissions as $permission)
            {
                "label": '{{ $permission->name }}',
                "value": '{{ $permission->id }}'
            },
            @endforeach
        ];
        VirtualSelect.init({
            ele: '#permissions',
            multiple: true,
            options: permissions,
        });
    </script>
    @endscript

</div>

But anyway I got "Unexpected token ‘:’" error and in browser I see :

enter image description here

"laravel/framework": "^10.48.4",
"livewire/livewire": "^3.4.9",

Thanks in advance!

2

Answers


  1. Chosen as BEST ANSWER

    I salved the issue with code in my blade :

    var permissionsListing = @json($permissionsListing)
    
        VirtualSelect.init({
            ele: '#permissions',
            multiple: true,
            options: permissionsListing,
        });
    

    Where array $permissionsListing in the component has label and value keys


  2. You should keep <script> ... </script> inside @script ... @endscript when using Livewire.
    Read more at Using JavaScript in Livewire components

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search