Search code examples
arraysobjectlaravel-livewirealpine.js

How to generate an array of objects in Alpine.data with Livewire Eloquent collection and Adding properties in those js objects


and thanks for your attention and help,

I have a Collection in my livewire controller. This collection contains a list of players, with some properties : here we will just focus on id and name. So we can imagine that we have 3 players in the collection :

Players[0] : 'id'=>1, 'name'=>'Yann';
Players[1] : 'id'=>2, 'name'=>'Robert';
Players[2] : 'id'=>3, 'name'=>'Jessica';

I need to get these players in my alpine data. I can easily get these players in Alpine with the @js method :

window.addEventListener('alpine:init', () => {
        Alpine.data('data', () => ({
            players: @js($players),
        }))
    })

So, now I have in my alpine.data :

players: [
               { id: 1, name: 'Yann' },
               { id: 2, name: 'Robert' },
               { id: 3, name: 'Jessica' },
    ]

Now I can easily display the players in my html with a template x-for :

<template x-for="player in players">
    <p x-text="player.name"></p>
</template>

But I want to add some additionnal properties in each player object. Those properties will be updated in front depending user's actions. I would like to get something like this :

players: [
              { id: 1, name: 'Yann', touched20: 0, touched15: 0 },
              { id: 2, name: 'Robert', touched20: 0, touched15: 0 },
              { id: 3, name: 'Jessica', touched20: 0, touched15: 0 },
   ]

All additionnal properties are the same for each object in the array, so I imagine i could use a foreach loop to put them in the objects. But I can't see and don't understand how i can include a loop in my alpine.data script to do this.

Anyone could help me ?


Solution

  • I edit my question because I found a solution :

    I just make a loopPlayers function outside of my alpine data and call this function in the alpine data :

    function loopPlayers() {
                let players = [];
                const livewirePlayers = @js($players);
                livewirePlayers.forEach(element => {
                    players.push(element);
                });
    
                players.forEach(function(element) {
                    element.touched15 = 0;
                    
                })
                return players;
            }
    

    And in alpine.data :

    players: loopPlayers(),
    

    Now I have my collection of players from my livewire controller & I have new properties for each element of the collection in the js data

    That was easy, as usual I guess :)