cinameng
cinameng

Reputation: 323

using Laravel array data in Alpine x-data directive

I have a Laravel array that I want to use in an Alpine.js component:

 $array = Names::get('name')->pluck('name')->toArray();

this stores the following data and sends it to the view:

array(3) { [0]=> string(3) "Foo" [1]=> string(3) "Bar" [2]=> string(3) "Baz" } 

my alpine component has the directive x-data (I am using the search example from the Getting Started page):

 x-data="{
    search: '',

    items: ['foo', 'bar', 'baz'],

    get filteredItems() {
        return this.items.filter(
            i => i.startsWith(this.search)
        )
    }
}"

I need to insert the data from $array to the x-data directive like this:

items: $array

however this is not displaying the data

I can't use the blade {{ }} as that will not echo an array

Upvotes: 2

Views: 5099

Answers (2)

bachstein
bachstein

Reputation: 23

if you are using livewire, you can always use alpine's entangle It accepts arrays

https://laravel-livewire.com/docs/2.x/alpine-js#sharing-state

Upvotes: 0

ruleboy21
ruleboy21

Reputation: 6371

Use @json() directive in blade. So your alpine component should look something like:

x-data="{
    search: '',

    items: @json($array),

    get filteredItems() {
        return this.items.filter(
            i => i.startsWith(this.search)
        )
    }
}"

Upvotes: 2

Related Questions