Search code examples
laravellaravel-livewire

Can't pass array to Livewire component with <livewire> element, only with Blade directive


I'm passing a $classes array, defined as a public property in my Livewire controller, to my Livewire component. When I use the blade directive:

@livewire('admin.syllabi', ['classes' => $classes, 'page' => $page, 'type' => 'syllabus', 'searchFields' => 'title, description'])

I can access my $classes array. However, when I use the livewire element:

<livewire:admin.syllabi
        page="{{ $page }}"
        type="syllabus"
        searchFields="title, description"
        classes="{{ $classes }}"
    />

I get the error,

htmlspecialchars(): Argument #1 ($string) must be of type string, array given.

I tried using : in front of the "classes" attribute in the element but then I get a different error:

"syntax error, unexpected token "<"

Has anyone got a solution for this?


Solution

  • To pass in variables or PHP expressions into the component using the "component syntax" <livewire:... />, you'll have to prefix the property with :, then it'll be parsed as a PHP expression like this,

    <livewire:admin.syllabi
        :page="$page"
        type="syllabus"
        searchFields="title, description"
        :classes="$classes"
    />
    

    This is a part of Blade and not limited to Livewire, as described in the official documentation, see the link below.

    https://laravel.com/docs/10.x/blade#passing-data-to-components